2012/7/19
linux下的i2c与时钟芯片pcf8563通信
by: 韩大卫 @吉林师范大学
1,本程序增加了对星期寄存器(wday)的写操作。
2, 本程序将i2c-test 改为rtdate 命令,并将rtdate作为最终命令发布。
3,在linux下,成功地在用户层操作了时钟芯片pcf8563的寄存器。
4,本程序考虑到了不同的系统中的rtc时钟芯片挂在不同的i2c bus的位置。、
比如:如果挂在 /dev/i2c-0 下,那么就只能打开/dev/i2c-0 进行操作,否则的话read/write 均会失败,那么这样就需要我们手动的传入参数,这需在程序中加入相应的判断条件。同时为了最大程度上做到便捷,如果不使用路径参数的话,那么程序中给出了默认路径/dev/i2c-1, 我们这样就可以直接
#rtdate -s 2012.7.19-19.36.00 修改硬件时间。
#rtdate -s 19.36.00 修改硬件时间
#rtdate -r 显示硬件时间
#rtdate -l 显示系统时间
需要手动加路径的话:
#rtdate -d /dev/i2c-10 -s 18:20:30
这样可以做到在不同的嵌入式系统中,不修改代码的情况下操作时钟芯片读写硬件时间,强化了软件的健壮性。
我们嵌入式系统中的cpu是Cavium Networks OCTEON CN5220,基于64bit的mips处理器。
********************************************* *******************************
转载请务必表明出处。 韩大卫@吉林师范大学。
********************************************** *******************************
main.c
**************** ******************************************
#include "i2c.h"
#define TIMEOUT 3
#define RETRY 3
static int fd;
static inline int is_leap_year(unsigned int year){
return (!(year % 4) && (year % 100)) || !(year % 400);
}
int rtc_month_days(unsigned int month, unsigned int year){
return rtc_days_in_month[month - 1] + (is_leap_year(year) && month == 1);
}
/*
* test year.mon.mday.wday.hour.min.sec
*/
int rtc_valid_tm(struct rtc_time *tm)
{
if( tm->tm_year < 1970
|| tm->tm_year >2069
|| ((unsigned)tm->tm_mon) > 12
|| tm->tm_mday < 0
|| tm->tm_mday > rtc_month_days(tm->tm_mon, tm->tm_year)
|| ((unsigned)tm->tm_hour) >= 24
|| ((unsigned)tm->tm_min) >= 60
|| ((unsigned)tm->tm_sec) >= 60)
return -EINVAL;
return 0;
}
/*
* test hour:min:sec
*/
int rtc_valid_half_tm(struct rtc_time *tm)
{
if((unsigned)tm->tm_hour >= 24 ||
(unsigned)tm->tm_min >= 60 ||
(unsigned)tm->tm_sec >= 60)
return -EINVAL;
return 0;
}
int i_open(unsigned char* dev, unsigned int timeout, unsigned int retry){
return i2c_open(dev,timeout,retry);
}
int read_data(u16 addr, u8 offset, u8 *val){
int ret;
ret = i2c_read_data(addr,offset,val);
if(ret < 0){
printf("%s error!\n",__FUNCTION__);
exit(-1);
}
return 0;
}
int write_data(u16 addr, u8 offset, u8 val){
int ret;
ret = i2c_write_data(addr,offset,val);
if(ret < 0){
printf("%s error!\n",__FUNCTION__);
exit(-1);
}
return 0;
}
int get_week_data(int y,int m,int d){
unsigned int w, c;
if (m <= 2){
m |= 4;
y--;
}
c = y/100;
c &= 0x03;
y %= 100;
w = ((c | (c << 2)) + (y + (y >> 2)) + (13 * m + 8)/ 5 + d) % 7;
return w;
}
/*
* -s YYYY.MM.DD-hh.mm.ss
*/
int time_year_begin(char* ptr,struct rtc_time* tm){
if( !(*(ptr+4) == '.' || *(ptr+4) == ':' )){
printf("TIME Format error !\n");
exit(-1);
}
u8 offset;
u16 addr = 0x51;
int i = 0;
int set_hour_flags = 0;
unsigned char buf[8] = {0};