- 树莓派本身没有RTC功能,若树莓派不联网则无法从网络获取正确时间,Pioneer 600扩展板上面带有高精度RTC时钟DS3231芯片,可解决这个问题。
一、配置RTC
1、 修改配置文件
sudo vi /boot/config.txt
添加RTC设备ds3231
dtoverlay=i2c-rtc,ds3231
重启树莓派生效设置,开机后可以运行lsmod命令查看时候有rtc-1307模块。
(注:ds3231为i2c控制,故应打开树莓派I2C功能)
2、 读取RTC时钟,
sudo hwclock -r
读取系统时间
date
3、 设置RTC时间
sudo hwclock --set --date=”2015/08/12 18:00:00”
4、 更新RTC时间到系统
sudo hwclock -s
5、 读取RTC时间及系统时间
sudo hwclock -r;date
二、编程控制
- 我们也可以通过I2C编程读写RTC时间,运行i2cdetect -y 1命令我们可以看到下图,我们发现ds3231的i2c地址0x68的位置显示UU,此时ds3231作为树莓派的硬件时钟,不能通过i2c编程控制,必须将刚才配置文件中的设置注释掉才能用。
sudo vi /boot/config.txt
找到刚才的设置,在前面加’#’注释掉
#dtoverlay=i2c-rtc,ds3231
重启后再运行i2cdetect -y ,此时发现ds3231可以通过i2c编程控制。
1、bcm2835
#include <bcm2835.h>
#include <stdio.h>
#include <unistd.h>
//regaddr,seconds,minutes,hours,weekdays,days,months,yeas
char buf[]={0x00,0x00,0x00,0x18,0x04,0x12,0x08,0x15};
char *str[] ={"SUN","Mon","Tues","Wed","Thur","Fri","Sat"};
void pcf8563SetTime()
{
bcm2835_i2c_write(buf,8);
}
void pcf8563ReadTime()
{
buf[0] = 0x00;
bcm2835_i2c_write_read_rs(buf ,1, buf,7);
}
int main(int argc, char **argv)
{
if (!bcm2835_init())return 1;
bcm2835_i2c_begin();
bcm2835_i2c_setSlaveAddress(0x68);
bcm2835_i2c_set_baudrate(10000);
printf("start..........\n");
pcf8563SetTime();
while(1)
{
pcf8563ReadTime();
buf[0] = buf[0]&0x7F; //sec
buf[1] = buf[1]&0x7F; //min
buf[2] = buf[2]&0x3F; //hour
buf[3] = buf[3]&0x07; //week
buf[4] = buf[4]&0x3F; //day
buf[5] = buf[5]&0x1F; //mouth
//year/month/day
printf("20%02x/%02x/%02x ",buf[6],buf[5],buf[4]);
//hour:minute/second
printf("%02x:%02x:%02x ",buf[2],buf[1],buf[0]);
//weekday
printf("%s\n",str[(unsigned char)buf[3]-1]);
bcm2835_delay(1000);
}
bcm2835_i2c_end();
bcm2835_close();
return 0;
}
编译并执行
gcc -Wall ds3231.c -o ds3231 -lbcm2835
sudo ./ds3231
2、python
#!/usr/bin/python
# -*- coding: utf-8 -*-
import smbus
import time
address = 0x68
register = 0x00
#sec min hour week day mout year
NowTime = [0x00,0x00,0x18,0x04,0x12,0x08,0x15]
w = ["SUN","Mon","Tues","Wed","Thur","Fri","Sat"];
#/dev/i2c-1
bus = smbus.SMBus(1)
def ds3231SetTime():
bus.write_i2c_block_data(address,register,NowTime)
def ds3231ReadTime():
return bus.read_i2c_block_data(address,register,7);
ds3231SetTime()
while 1:
t = ds3231ReadTime()
t[0] = t[0]&0x7F #sec
t[1] = t[1]&0x7F #min
t[2] = t[2]&0x3F #hour
t[3] = t[3]&0x07 #week
t[4] = t[4]&0x3F #day
t[5] = t[5]&0x1F #mouth
print("20%x/%x/%x %x:%x:%x %s" %(t[6],t[5],t[4],t[2],t[1],t[0],w[t[3]-1]))
time.sleep(1)
执行程序
sudo python ds3231.py