日期:2014-05-16  浏览次数:20674 次

IIC使用外部寄存器的问题【高分求助】
我在2410板子上向C02寄存器中读写数据没有任何问题,但在使用外部IIC的时候却始终有问题,读出的数据和写入的数据完全不一样,大家帮我分析下,我的IIC程序如下:/************************************
* *GEC-2410-BOX
* *eeprom at24c02 test program
************************************/
#include <stdio.h>
#include <fcntl.h>

#include <linux/i2c.h>
#include <linux/i2c-dev.h>

#define CHIP_ADDR 0x3F
#define PAGE_SIZE 0x08
#define I2C_DEV_PATH "/dev/i2c-0"

static int read_eeprom(int fd, char buff[], int addr, int count)
{
int res;
if(write(fd, &addr, 1) != 1)
return -1;

res=read(fd, buff, count);
printf("read %d byte at 0x%.2x\n", res, addr);

return res;
}

static int write_eeprom(int fd, char buff[], int addr, int count)
{
int res;
int i;
char sendbuffer[PAGE_SIZE+1];

memcpy(sendbuffer+1, buff, count);
sendbuffer[0]=addr;

res= write(fd, sendbuffer, count+1);
printf("write %d byte at 0x%.2x\n", res ,addr);
}

int main(void)
{
int fd, n, res;
unsigned char buf[PAGE_SIZE];

fd = open(I2C_DEV_PATH, O_RDWR);
if(fd < 0)
{
printf("####i2c test device open fail####\n");
return (-1);
}
printf("success, i2c open file device %d \n",fd);


res = ioctl(fd, I2C_TENBIT,0); //do not use 10bit address mode
res = ioctl(fd, I2C_SLAVE_FORCE,CHIP_ADDR); //set slave device address
printf("ioctl I2C_SLAVE_FORCE msg NO:%d\n",res);

for(n=0; n<PAGE_SIZE; n++)
buf[n]=n+1;

write_eeprom(fd, buf, 0, sizeof(buf));
read_eeprom(fd, buf, 0, sizeof(buf));


for(n=0; n<sizeof(buf); n++) {
printf("0x%.2x, ", buf[n]);
}
printf("\n");

close(fd);
return(0);
}

从地址是0X3F,从地址下分别是0X00.0X01,0X02等地址,我想向0X00的地址读写数据,可老师失败,没任何提示,但数据对不上,哪位大人帮我看看

------解决方案--------------------
汗。。你的问题居然没人回复,帮你顶下吧。

QT界面跳转的那个错误搞定了没?还没搞定的话,我贴代码你算了。。
------解决方案--------------------
举例来说,假如一个I2C总线上有两个设备,地址为0x40和0x50。
第一步,打开总线/dev/i2c-x,此处x代表总线号,如第一根i2c总线就是i2c-0,第二根i2c总线就是i2c-1,依此类推。
int file;
int adapter_nr = 2; /* probably dynamically determined */
char filename[20];
  
sprintf(filename,"/dev/i2c-%d",adapter_nr);
if ((file = open(filename,O_RDWR)) < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
exit(1);
}

第二步,对I2C总线(第一步打开的总线)进行一些ioctl操作,如
I2C_TENBIT是说明I2C总线(第一步打开的总线)上的待访问设备的地址是7bits地址还是10bits地址

第三步,指定I2C总线(第一步打开的总线)上的待访问设备的地址
int addr = 0x40; /* The I2C address */
if (ioctl(file,I2C_SLAVE,addr) < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
exit(1);
}

第四步,对I2C总线(第一步打开的总线)进行read/write操作,也可以通过i2c-core.c中提供的API进行读写操作。如
__u8 register = 0x10; /* Device register to access */
__s32 res;
char buf[10];
/* Using SMBus commands */
res = i2c_smbus_read_word_data(file,register);
if (res < 0) {
/* ERROR HANDLING: i2c transaction failed */
} else {
/* res contains the read word */
}
/* Using I2C Write, equivalent of 
i2c_smbus_write_word_data(file,register,0x6543) */
buf[0] = register;
buf[1] = 0x43;
buf[2] = 0x65;
if ( write(file,buf,3) != 3) {
/* ERROR HANDLING: i2c transaction failed */
}

第五步,关闭I2C总线(第一步打开的总线)
close(file);


------解决方案--------------------
探讨
引用:
汗。。你的问题居然没人回复,帮你顶下吧。