能给一个at24c256的C语言驱动代码吗?
时间: 2024-03-15 16:44:10 浏览: 71
当然可以,以下是一个基于I2C总线的AT24C256 EEPROM的C语言驱动代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#define I2C_BUS "/dev/i2c-1"
#define EEPROM_ADDR 0x50
int i2c_fd;
void i2c_init() {
i2c_fd = open(I2C_BUS, O_RDWR);
if (i2c_fd < 0) {
perror("open i2c bus failed");
exit(EXIT_FAILURE);
}
}
void i2c_deinit() {
close(i2c_fd);
}
int i2c_write(unsigned char *buf, int len) {
if (write(i2c_fd, buf, len) != len) {
perror("write i2c bus failed");
return -1;
}
return 0;
}
int i2c_read(unsigned char *buf, int len) {
if (read(i2c_fd, buf, len) != len) {
perror("read i2c bus failed");
return -1;
}
return 0;
}
void eeprom_write(unsigned short addr, unsigned char *buf, int len) {
unsigned char write_buf[256];
int i;
write_buf[0] = addr >> 8;
write_buf[1] = addr & 0xFF;
for (i = 0; i < len; i++) {
write_buf[i + 2] = buf[i];
}
i2c_write(write_buf, len + 2);
usleep(10000); // 10ms delay
}
void eeprom_read(unsigned short addr, unsigned char *buf, int len) {
unsigned char write_buf[2];
write_buf[0] = addr >> 8;
write_buf[1] = addr & 0xFF;
i2c_write(write_buf, 2);
i2c_read(buf, len);
}
int main() {
unsigned char buf[256];
unsigned short addr = 0x0000;
int i;
i2c_init();
// write data to eeprom
for (i = 0; i < 256; i++) {
buf[i] = i;
}
eeprom_write(addr, buf, 256);
// read data from eeprom
for (i = 0; i < 256; i++) {
buf[i] = 0;
}
eeprom_read(addr, buf, 256);
for (i = 0; i < 256; i++) {
printf("%02X ", buf[i]);
if ((i + 1) % 16 == 0) {
printf("\n");
}
}
i2c_deinit();
return 0;
}
```
这是一个基本的驱动程序框架,你可以根据具体的应用场景进行修改和优化。
阅读全文