Created
August 28, 2021 11:09
-
-
Save Zibri/cf8ac0b311301aeeaa8910c7da824bff to your computer and use it in GitHub Desktop.
24c256 backup and restore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Utility to dump and restore a 24c256 eeprom. | |
(Changing the defines it will work with other eeproms too.) | |
Remember that 24c256 has 16 bit addressing. | |
Smaller ones have 8 bit addressing. | |
By Zibri. | |
Usage: 24c256br /dev/i2c-X >eep_dump.bin to dump. | |
24c256br /dev/i2c-X <eep_dump.bin to restore. | |
*/ | |
#include <stdio.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <sys/ioctl.h> | |
#include <linux/i2c-dev.h> | |
#define READ_SIZE (256) | |
#define NB_PAGES (128) | |
#define WRITE_SIZE (64) | |
#define WRITE_PAGES (512) | |
int main(int argc, char *argv[]) | |
{ | |
if ((isatty(0) && isatty(1)) || argc != 2) { | |
dprintf(2, "Usage:\t%s /dev/i2c-X >eep_dump.bin to dump.\n\t%s /dev/i2c-X <eep_dump.bin to restore.\n", argv[0], argv[0]); | |
return 1; | |
} | |
const int device_address = 0x50; | |
int file = open(argv[1], O_RDWR); | |
if (file < 0) { | |
printf("Failed opening %s\n", argv[1]); | |
return 1; | |
} | |
if (ioctl(file, I2C_SLAVE, device_address) < 0) { | |
printf("Failed addressing device at %02X\n", device_address); | |
close(file); | |
return 1; | |
} | |
if (!isatty(1)) { // if stdout is redirected then DUMP | |
int i = 0; | |
char buf[32768] = { 0 }; | |
write(file, buf, 2); // set address to 0 | |
usleep(5000); | |
for (i = 0; i < NB_PAGES; i++) { | |
if (read(file, buf, READ_SIZE) != READ_SIZE) { | |
dprintf(2, "Failed reading\n"); | |
close(file); | |
return 1; | |
} | |
write(1, buf, READ_SIZE); | |
} | |
} else { // stdout is not redirected but stdin is so WRITE | |
int i = 0; | |
for (i = 0; i < WRITE_PAGES; i++) { | |
char buf[WRITE_SIZE + 2] = { 0 }; | |
int isw = i * WRITE_SIZE; | |
buf[0] = (isw >> 8) & 0xff; // HI ADDR | |
buf[1] = isw & 0xff; // LO ADDR | |
if (read(0, buf + 2, WRITE_SIZE) != WRITE_SIZE) { | |
dprintf(2, "Failed reading\n"); | |
return 1; | |
} | |
write(file, buf, WRITE_SIZE + 2); | |
int rdy = 0; | |
do { // Acknowledge Polling :D | |
rdy = write(file, buf, 2); | |
} while (rdy != 2); | |
} | |
} | |
close(file); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment