为树莓派 添加一个 实时时钟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()函数 ,用来设置引脚,修改如图:
- int main(int argc, char *argv[])
- {
- int i;
- int clock[8];
-
- wiringPiSetup();
- //ds1308setup(0,1,2);
- ds1302setup(14,10,30);
-
- if(argx == 2)
- {
- /**/if(strcmp(argv[1],"-slc") == 0)
- return setLinuxClocl();
- else if(strcmp(argv[1],"-sdsc") == 0)
- return setDSclock();
- else if(strcmp(argv[1],"-rtest") == 0)
- return ramTest();
- else
- {
- printf("Usage:ds1302[-slc|-sdsc|-rtest]\n");
- return EXIT_FAILURE;
- }
- }
-
- }
复制代码 这里的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()函数 如下:
- static int setDSclock (void)
- {
- //struct tm t ;
- struct tm* t = NULL;
- time_t now ;
- int clock [8] ;
-
- printf ("Setting the clock in the DS1302 from Linux time... ") ;
-
- now = time (NULL) ;
- //gmtime_r (&now, &t) ;
- t = localtime(&now);
-
- //clock [ 0] = dToBcd (t.tm_sec) ; // seconds
- //clock [ 1] = dToBcd (t.tm_min) ; // mins
- //clock [ 2] = dToBcd (t.tm_hour) ; // hours
- //clock [ 3] = dToBcd (t.tm_mday) ; // date
- //clock [ 4] = dToBcd (t.tm_mon + 1) ; // months 0-11 --> 1-12
- //clock [ 5] = dToBcd (t.tm_wday + 1) ; // weekdays (sun 0)
- //clock [ 6] = dToBcd (t.tm_year - 100) ; // years
- //clock [ 7] = 0 ; // W-Protect off
-
- clock [ 0] = dToBcd (t->tm_sec) ; // seconds
- clock [ 1] = dToBcd (t->tm_min) ; // mins
- clock [ 2] = dToBcd (t->tm_hour) ; // hours
- clock [ 3] = dToBcd (t->tm_mday) ; // date
- clock [ 4] = dToBcd (t->tm_mon + 1) ; // months 0-11 --> 1-12
- clock [ 5] = dToBcd (t->tm_wday + 1) ; // weekdays (sun 0)
- clock [ 6] = dToBcd (t->tm_year - 100) ; // years
- clock [ 7] = 0 ; // W-Protect off
-
- ds1302clockWrite (clock) ;
-
- 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 重新执行以上指令即可获取当地时间了
|
|
|
|