我在2410linux下面运行通过read()、write()接口和O_RDWR IOCTL读写I2C设备的程序:
#include
#include
#include
#include
#include
#include
#include
#define I2C_RETRIES 0x0701
#define I2C_TIMEOUT 0x0702
#define I2C_SLAVE 0x0703
#define I2C_DEV "dev/i2c-0"
int main(int argc, char **argv)
{
unsigned int fd;
unsigned short mem_addr;
unsigned short size;
unsigned short idx;
#define BUFF_SIZE 32
char buf[BUFF_SIZE];
char cswap;
union
{
unsigned short addr;
char bytes[2];
} tmp;
if (argc < 3)
{
printf("Use:\n%s /dev/i2c-x mem_addr size\n", argv[0]);
return 0;
}
sscanf(argv[2], "%d", &mem_addr);
sscanf(argv[3], "%d", &size);
if (size > BUFF_SIZE)
size = BUFF_SIZE;
fd = open(argv[1], O_RDWR);
if (!fd)
{
printf("Error on opening the device file\n");
return 0;
}
ioctl(fd, I2C_SLAVE, 0x50); /* 设置eeprom地址 */
ioctl(fd, I2C_TIMEOUT, 1); /* 设置超时 */
ioctl(fd, I2C_RETRIES, 1); /* 设置重试次数 */
for (idx = 0; idx < size; ++idx, ++mem_addr)
{
tmp.addr = mem_addr;
cswap = tmp.bytes[0];
tmp.bytes[0] = tmp.bytes[1];
tmp.bytes[1] = cswap;
write(fd,&tmp.addr,2);
read(fd, &buf[idx], 1);
}
buf[size] = 0;
close(fd);
printf("Read %d char: %s\n", size, buf);
return 0;
}
为什么输出的buf是乱码啊,哪位达人帮我看下好吗!!
整了一天,发觉问题更多了,
sscanf(argv[2], "%d", &mem_addr);
在上面这句中,应该是给mem_addr赋值吧,可我在这句后面加上printf输出mem_addr的值却得到mem_addr=0,很明显赋值失败头大了,有人能告诉我为什么吗?