用C语言写一个AT24C08 eeprom的驱动程序
时间: 2023-05-11 14:07:08 浏览: 153
好的,以下是一个简单的AT24C08 EEPROM的驱动程序示例,使用C语言编写:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#define EEPROM_ADDR 0x50 // EEPROM的I2C地址
#define EEPROM_SIZE 2048 // EEPROM的大小
int eeprom_fd; // EEPROM文件描述符
// 初始化EEPROM
int eeprom_init() {
char *dev = "/dev/i2c-1"; // I2C设备文件
if ((eeprom_fd = open(dev, O_RDWR)) < 0) {
perror("open");
return -1;
}
if (ioctl(eeprom_fd, I2C_SLAVE, EEPROM_ADDR) < 0) {
perror("ioctl");
return -1;
}
return 0;
}
// 读取EEPROM中的数据
int eeprom_read(unsigned int addr, unsigned char *buf, unsigned int len) {
if (addr + len > EEPROM_SIZE) {
return -1;
}
if (write(eeprom_fd, &addr, sizeof(addr)) != sizeof(addr)) {
perror("write");
return -1;
}
if (read(eeprom_fd, buf, len) != len) {
perror("read");
return -1;
}
return 0;
}
// 写入数据到EEPROM中
int eeprom_write(unsigned int addr, unsigned char *buf, unsigned int len) {
if (addr + len > EEPROM_SIZE) {
return -1;
}
unsigned char *data = (unsigned char *)malloc(len + sizeof(addr));
if (data == NULL) {
perror("malloc");
return -1;
}
memcpy(data, &addr, sizeof(addr));
memcpy(data + sizeof(addr), buf, len);
if (write(eeprom_fd, data, len + sizeof(addr)) != len + sizeof(addr)) {
perror("write");
free(data);
return -1;
}
free(data);
return 0;
}
// 关闭EEPROM
void eeprom_close() {
close(eeprom_fd);
}
int main() {
// 初始化EEPROM
if (eeprom_init() < 0) {
printf("Failed to initialize EEPROM\n");
return -1;
}
// 读取EEPROM中的数据
unsigned char buf[16];
if (eeprom_read(0x00, buf, sizeof(buf)) < 0) {
printf("Failed to read EEPROM\n");
eeprom_close();
return -1;
}
printf("Read data from EEPROM: ");
for (int i = 0; i < sizeof(buf); i++) {
printf("%02X ", buf[i]);
}
printf("\n");
// 写入数据到EEPROM中
unsigned char data[] = {0x01, 0x02, 0x03, 0x04, 0x05};
if (eeprom_write(0x10, data, sizeof(data)) < 0) {
printf("Failed to write EEPROM\n");
eeprom_close();
return -1;
}
printf("Write data to EEPROM successfully\n");
// 关闭EEPROM
eeprom_close();
return 0;
}
阅读全文