例子1
读取eeprom里的内容:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc!= 2) {
printf("Usage: %s <address>\n", argv[0]);
return -1;
}
int fd;
int address = (int)strtol(argv[1], NULL, 0);
char buf[1024] = {0};
fd = open("/sys/bus/i2c/devices/0-0056/eeprom", O_RDWR);
if (fd < 0) {
printf("####i2c test device open failed####\n");
return -1;
}
if (lseek(fd, address, SEEK_SET) < 0) {
printf("Failed to seek to address 0x%x.\n", address);
close(fd);
return 1;
}
ssize_t size = read(fd, buf, sizeof(buf));
if (size < 0) {
printf("read error at address 0x%x\n", address);
close(fd);
return 1;
}
printf("Data at address 0x%x:\n", address);
for (int i = 0; i < size; i++) {
printf("%02x ", buf[i]);
}
printf("\n");
close(fd);
return 0;
}
./test 0x4
例子2:
可以读出16进制数据 还以要转话成字符串:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
if (argc!= 2) {
printf("Usage: %s <address>\n", argv[0]);
return -1;
}
int fd;
int address = (int)strtol(argv[1], NULL, 0);
char buf[1024] = {0};
fd = open("/sys/bus/i2c/devices/0-0056/eeprom", O_RDWR);
if (fd < 0) {
printf("####i2c test device open failed####\n");
return -1;
}
if (lseek(fd, address, SEEK_SET) < 0) {
printf("Failed to seek to address 0x%x.\n", address);
close(fd);
return 1;
}
ssize_t size = read(fd, buf, sizeof(buf));
if (size < 0) {
printf("read error at address 0x%x\n", address);
close(fd);
return 1;
}
// 找到第一个 null 字符并截断字符串
for (int i = 0; i < size; i++) {
if (buf[i] == '\0') {
size = i;
break;
}
}
// 将缓冲区转换为字符串并打印
char *str = (char *)malloc(size + 1);
memcpy(str, buf, size);
str[size] = '\0';
printf("Data at address 0x%x as string: %s\n", address, str);
free(str);
close(fd);
return 0;
}