by 韩大卫@吉林师范大学
handawei@jusontech.com
转载请务必表明出处。
我的上篇文章《Linux下使用I2C总线读写 EEPROM(读写i2c从设备通用程序)》给出了通过IIC总线,如何读写EEPROM相应位置的内容。
但是有一些功能没有实现:
比如: 只能单独操作一个寄存器地址,不能一次性写入大量内容;
只能读一个寄存器的数值,不能可选择性地一次读出大量内容;
这是由于为了做到通用化,我们的i2c没有一次性大量读写的功能。 在本程序中针对EEPROM做了一些改进,详细说明可以在help_info() 中找到。
FOR EXAMPLE:
eep -r 0x08 Display the contents of EEPROM from 0x00 to 0x08
eep -ro 0x08 Display the contents of EEPROM from 0x08
eep -r 0x02 0x80 Display the contents of EEPROM from address 0x20 to x080
eep -s 0x04 "hello world!" Write "hello world!" to EEPROM from 0x04
eep -d /dev/i2c-1 -s 0x04 "hello world!" Write "hello world!" to EEPROM from 0x04 with path"/dev/i2c-1"
*************************************************************
main.c
********************** *******************************
#include "i2c.h"
#define TIMEOUT 4
#define RETRY 2
#define READ_ONLY 1
static int fd ;
static int addr = 0x57; // EEPROM addr
static int offset;
static int offset_end;
inline 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;
}
inline int write_data(u16 addr, u8 offset, u8 val){
int ret;
ret = i2c_write_data(addr,offset,val);
if(ret < 0){
printf("%s:error = %s\n",__FUNCTION__,strerror(errno));
exit(-1);
}
usleep(10000); // 重要!
return 0;
}
int eep_write(u16 addr,u8 offset,char* argv){
//u8 data = (u8)strtoul(argv,0,16);
int i,j,len = 0;
char* data = argv;
while( *data++ ){
len++;
}
data = argv;
printf("len = %d\n",len);
for( i = offset ,j = 0;i < offset + len ;i++,j++ ){
write_data(addr,i,data[j]);
}
printf("write success,data = %s\n",argv);
return 0;
}
int eep_read(u16 addr,u8 offset_start,u8 offset_end,int flags){
int i;
u8 buf[256] = {0};
if( flags ){
read_data(addr,offset_end,&am