加入收藏 | 设为首页 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > 学习资料

为树莓派 添加一个 实时时钟DS1302

时间:2021-03-21 20:17:53  来源:  作者:
1、在系统中安装wiringPi(这个就不多说了很简单)
2、连接ds1302模块和树莓派引脚
连接前需要在ds1302的DTA引脚上添加一个10K的上拉电阻,
VCC—3.3V—-
GND—0V—-
CLK—SCLK—-23
DTA—SDA0—-24
RST—CE0—–27
3、修改程序
ds1302.c的mian函数里有一个ds1302setup()函数 ,用来设置引脚,修改如图:
 
  1. int main(int argc, char *argv[])
  2. {
  3. int i;
  4. int clock[8];
  5.  
  6. wiringPiSetup();
  7. //ds1308setup(0,1,2);
  8. ds1302setup(14,10,30);
  9.  
  10. if(argx == 2)
  11. {
  12.   /**/if(strcmp(argv[1],"-slc") == 0)
  13.    return setLinuxClocl();
  14.   else if(strcmp(argv[1],"-sdsc") == 0)
  15.    return setDSclock();
  16.   else if(strcmp(argv[1],"-rtest") == 0)
  17.    return ramTest();
  18.   else
  19.   {
  20.   printf("Usage:ds1302[-slc|-sdsc|-rtest]\n");
  21.   return EXIT_FAILURE;
  22.   }
  23. }
  24.  
  25. }
复制代码
这里的14,10,30引脚号是wPi的编号不要弄错了


在wiringPi/examples目录下有ds1302.c文件 在wiringPi/examples目录下执行make ds1302即可生产可执行文件ds1302
4、测试
4.1 执行sudo ./ds1302 -rtest
显示:

说明一切正常,否者请检查连接是否正确
4.2 sudo ./ds1302 -sdsc 即可将系统时间写进ds1302模块中去
4.3 从DS模块读取时间
执行sudo ./ds1302

4.4 从DS模块读取时间来设置系统的时间
sudo ./ds1302 -slc
5、获取当地时间 (以上获取的是UTC(Coordinated Universal Time)时间到当前时刻的秒数,要想从该秒数转换成本地时间需要用localtime()函数struct tm *localtime(const time_t *clock),)
修改ds1302.c中的setDSclock()函数
如下:
  1. static int setDSclock (void)
  2. {
  3.   //struct tm t ;
  4.   struct tm* t = NULL;
  5.   time_t now ;
  6.   int clock [8] ;
  7.  
  8.   printf ("Setting the clock in the DS1302 from Linux time... ") ;
  9.  
  10.   now = time (NULL) ;
  11.   //gmtime_r (&now, &t) ;
  12.   t = localtime(&now);
  13.   
  14.   //clock [ 0] = dToBcd (t.tm_sec) ;        // seconds
  15.   //clock [ 1] = dToBcd (t.tm_min) ;        // mins
  16.   //clock [ 2] = dToBcd (t.tm_hour) ;        // hours
  17.   //clock [ 3] = dToBcd (t.tm_mday) ;        // date
  18.   //clock [ 4] = dToBcd (t.tm_mon + 1) ;        // months 0-11 --> 1-12
  19.   //clock [ 5] = dToBcd (t.tm_wday + 1) ;        // weekdays (sun 0)
  20.   //clock [ 6] = dToBcd (t.tm_year - 100) ;       // years
  21.   //clock [ 7] = 0 ;                        // W-Protect off
  22.   
  23.   clock [ 0] = dToBcd (t->tm_sec) ;        // seconds
  24.   clock [ 1] = dToBcd (t->tm_min) ;        // mins
  25.   clock [ 2] = dToBcd (t->tm_hour) ;        // hours
  26.   clock [ 3] = dToBcd (t->tm_mday) ;        // date
  27.   clock [ 4] = dToBcd (t->tm_mon + 1) ;        // months 0-11 --> 1-12
  28.   clock [ 5] = dToBcd (t->tm_wday + 1) ;        // weekdays (sun 0)
  29.   clock [ 6] = dToBcd (t->tm_year - 100) ;       // years
  30.   clock [ 7] = 0 ;                        // W-Protect off
  31.  
  32.   ds1302clockWrite (clock) ;
  33.  
  34.   printf ("OK\n %2d:%02d\n %2d:%02d\n",t->tm_hour,t->tm_min,dToBcd (t->tm_hour),dToBcd (t->tm_min) ) ;
复制代码

之后重新编译make ds1302 重新执行以上指令即可获取当地时间了

 
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
实现php间隔一段时间执行一次某段代码
实现php间隔一段时间
相关文章
    无相关信息
栏目更新
栏目热门