linux i2c读写eeprom代码
时间: 2023-09-02 10:09:38 浏览: 75
以下是一个简单的 Linux C 代码示例,用于通过 I2C 接口读写 EEPROM:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#define EEPROM_ADDR 0x50
#define EEPROM_SIZE 256
int main()
{
int file;
char filename[20];
char data[EEPROM_SIZE];
int i;
sprintf(filename, "/dev/i2c-1");
if ((file = open(filename, O_RDWR)) < 0) {
perror("Failed to open the i2c bus");
exit(1);
}
if (ioctl(file, I2C_SLAVE, EEPROM_ADDR) < 0) {
perror("Failed to acquire bus access and/or talk to slave");
exit(1);
}
// 读取 EEPROM 数据
if (read(file, data, EEPROM_SIZE) != EEPROM_SIZE) {
perror("Failed to read from the i2c bus");
} else {
printf("Read data from EEPROM:\n");
for (i = 0; i < EEPROM_SIZE; i++) {
printf("%02x ", data[i]);
if ((i + 1) % 16 == 0) printf("\n");
}
}
// 写入 EEPROM 数据
for (i = 0; i < EEPROM_SIZE; i++) {
data[i] = i;
}
if (write(file, data, EEPROM_SIZE) != EEPROM_SIZE) {
perror("Failed to write to the i2c bus");
} else {
printf("Wrote data to EEPROM\n");
}
close(file);
return 0;
}
```
在上面的代码中,我们首先打开 /dev/i2c-1 设备节点,这是 I2C 接口的默认节点。然后我们使用 ioctl 函数设置从设备地址为 0x50 的 EEPROM 作为通信目标。接下来,我们使用 read 函数从 EEPROM 中读取 256 字节的数据,并使用 write 函数将 0 到 255 的数据写入 EEPROM 中。请注意,这是一个简单的示例,实际应用中需要根据 EEPROM 的型号和规格进行适当的修改。