26781 views|1 replies

156

Posts

1

Resources
The OP
 

[Raspberry Pi 3B+ Review] Open I2C peripheral interface & drive DS3231 [Copy link]

This post was last edited by donatello1996 on 2018-12-24 00:05 This post uses a very simple method to use the Raspberry Pi to communicate with the I2C device. The device is selected as the DS3231 with the I2C interface. Simply connect the DS3231 to the I2C-1 interface: First, enable the I2C peripheral interface of the Raspberry Pi, either in the desktop settings or in the BOOT configuration file: Then use the command line tool i2cdetect to detect the existence of the I2C interface and the I2C slave: i2cdetect -y 1 i2cdump -y 1 0x68 You can see that the first seven registers of DS3231 are time data, from 0x01 to 0x07, they are seconds, minutes, hours, days, months, and years. Then load the wiringPi library, read the time from the program and display it: #ifndef _DS3231_H_ #define _DS3231_H_ #include


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

看看效果:

This post is from Embedded System

Latest reply

Nice guy, well written, keep it up!  Details Published on 2018-12-24 10:54

6040

Posts

204

Resources
2
 
Nice guy, well written, keep it up!
This post is from Embedded System
 
 

Guess Your Favourite
Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list