【树莓派3B+测评】打开I2C外设接口&驱动DS3231
本帖最后由 donatello1996 于 2018-12-24 00:05 编辑本帖使用一个非常简单的方法用树莓派与I2C器件通信,这个器件选为I2C接口的DS3231,直接把DS3231接到I2C-1接口中即可:
首先要启用树莓派的I2C外设接口,在桌面设置或者BOOT配置文件下都可以:
然后是使用命令行工具i2cdetect检测I2C接口和I2C从机的存在:
i2cdetect -y 1
i2cdump -y 1 0x68
可以看到,DS3231前七个寄存器数据就是时间数据,从0x01~0x07依次为秒 分 时 星期 日 月 年。
然后加载wiringPi库,从程序中读取时间并显示:
#ifndef _DS3231_H_
#define _DS3231_H_
#include <wiringPiI2C.h>
unsigned char BCD_to_BYTE(unsigned char val)
//BCD转换为Byte
{
return((val>>4)*10)+(val&0x0f);
}
unsigned char BYTE_to_BCD(unsigned char val)
//Byte码转换为BCD码
{
return(((val%100)/10)<<4)|(val%10);
}
unsigned char fd_i2c_ds3231,hour,min,sec,day,year,month,date;
void DS3231_Init(int flag,unsigned char year,unsigned char month,unsigned char date,
unsigned char day,unsigned char hour,unsigned char min,unsigned char sec)
{
fd_i2c_ds3231=wiringPiI2CSetup(0x68);
if(flag)
{
wiringPiI2CWriteReg8(fd_i2c_ds3231,6,BYTE_to_BCD(year));
wiringPiI2CWriteReg8(fd_i2c_ds3231,5,BYTE_to_BCD(month));
wiringPiI2CWriteReg8(fd_i2c_ds3231,4,BYTE_to_BCD(date));
wiringPiI2CWriteReg8(fd_i2c_ds3231,3,BYTE_to_BCD(day));
wiringPiI2CWriteReg8(fd_i2c_ds3231,2,BYTE_to_BCD(hour));
wiringPiI2CWriteReg8(fd_i2c_ds3231,1,BYTE_to_BCD(min));
wiringPiI2CWriteReg8(fd_i2c_ds3231,0,BYTE_to_BCD(sec));
}
}
void DS3231_Read()
{
sec=wiringPiI2CReadReg8(fd_i2c_ds3231,0);
sec=BCD_to_BYTE(sec);
min=wiringPiI2CReadReg8(fd_i2c_ds3231,1);
min=BCD_to_BYTE(min);
hour=wiringPiI2CReadReg8(fd_i2c_ds3231,2);
hour=BCD_to_BYTE(hour);
day=wiringPiI2CReadReg8(fd_i2c_ds3231,3);
date=wiringPiI2CReadReg8(fd_i2c_ds3231,4);
date=BCD_to_BYTE(date);
month=wiringPiI2CReadReg8(fd_i2c_ds3231,5);
month=BCD_to_BYTE(month);
year=wiringPiI2CReadReg8(fd_i2c_ds3231,6);
year=BCD_to_BYTE(year);
}
#endif
看看效果:
不错小伙子,写的很好,加油!
页:
[1]