#include #include #include #include #include #include #define DEV "/dev/i2c/0" #define EEPROM_ADDR 0x50 int i2cdev; void i2c_readpage(unsigned char page_start, unsigned char *dest) { // Read 8-byte page if (write(i2cdev, &page_start, 1) != 1) perror("address_write"); if (read(i2cdev, dest, 8) != 8) perror("data_read"); } void i2c_writepage(unsigned char page_start, unsigned char *src) { // Write 8-byte page unsigned char buf[9]; buf[0] = page_start; memcpy(buf + 1, src, 8); if (write(i2cdev, buf, 9) != 9) perror("data_write"); while (write(i2cdev, "\x00", 1) != 1) // Busy loop usleep(1000); i2c_readpage(page_start, buf); // Verify if (memcmp(buf, src, 8) != 0) fprintf(stderr, "I2C eeprom data compare failed\n"); } void savefile(char *filename) { FILE *file = fopen(filename, "w"); int addr, i; unsigned char buf[8]; for (addr = 0; addr < 0x100; addr += 8) { i2c_readpage(addr, buf); for (i = 0; i < 8; i++) { fprintf(file, "%02x ", buf[i]); } fprintf(file, "// 0x%02x - 0x%02x\n", addr, addr + 7); } fclose(file); } void loadfile(char *filename) { FILE *file = fopen(filename, "r"); int addr = 0; char linebuf[256]; unsigned char buf[8]; while (fgets(linebuf, 256, file) && addr < 0x100) { int i; char *p = linebuf; for (i = 0; i < 8; i++) { buf[i] = strtol(p, NULL, 16); p += 3; if (!isspace(*(p - 1))) fprintf(stderr, "Invalid format at 0x%02x\n", addr); } i2c_writepage(addr, buf); addr += 8; } fclose(file); } int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s load|save file\n", argv[0]); exit(1); } i2cdev = open(DEV, O_RDWR); if (i2cdev < 0) perror("open"); if (ioctl(i2cdev, I2C_SLAVE, EEPROM_ADDR) < 0) perror("ioctl"); if (strcmp(argv[1], "load") == 0) { loadfile(argv[2]); } else if (strcmp(argv[1], "save") == 0) { savefile(argv[2]); } else { fprintf(stderr, "Invalid command %s\n", argv[1]); } return 0; }