把前面的 ioctl 用法與 AT24C02 的時序規則合起來,就可以寫一個小小的測試程式了。
測試環境:TQ2440 開發板 + 板載 AT24C02;內核版本 linux-2.6.37.1。讀與寫拆成兩個獨立的程式,各自專注一件事,出問題時比較容易定位。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
int main(int argc, char *argv[])
{
int num, err, i;
int fd;
char *buff;
printf("please input as: ./wat24 [addr] [data...]\n");
fflush(stdout);
if (argc < 3) {
printf("arg error\n");
return -1;
}
num = argc - 1;
buff = malloc(num * sizeof(char));
if (buff == NULL) {
printf("alloc failed\n");
return -1;
}
buff[0] = atoi(argv[1]); /* 起始 word address */
printf("write data:\n");
for (i = 1; i < num; i++) {
buff[i] = atoi(argv[i + 1]);
printf("%d\n", buff[i]);
}
printf("from word addr:%d\n", buff[0]);
fd = open("/dev/i2c-0", O_RDWR);
if (fd < 0) {
printf("device open failed\n");
return -1;
}
err = ioctl(fd, I2C_SLAVE_FORCE, 0x50);
if (err < 0) {
printf("ioctl failed:%d\n", err);
return -1;
}
write(fd, buff, num);
close(fd);
return 0;
}
如果 open 失敗,先確認 adapter driver 是否已註冊、/dev/i2c-0 是否存在;如果 ioctl 回報失敗,多半是位址不對或器件沒有回應 ACK;如果寫入後讀回不一致,則要回頭檢查是否超過 8 byte 而觸發了頁內覆蓋,以及起始位址是否按頁對齊。讀取程式若需要 random read,就得改用 I2C_RDWR 投遞兩則 msg,而不能用 read()。
I2C 子系統系列:ioctl()、at24c02 簡介、總結、write()。
https://www.linuxidc.com/Linux/2012-08/68257.htm
https://www.linuxidc.com/Linux/2012-08/68258.htm
https://www.linuxidc.com/Linux/2012-08/68259.htm
https://www.linuxidc.com/Linux/2012-08/68268.htm