Using an I2C EEPROM (AT24C32) with Arduino

First off, there are already a whole bunch of tutorials on how to use this particular I2C EEPROM with an Arduino. If you want to understand how such an EEPROM works, this post is not for you.

I just wanted to share this bit of code with anyone who doesn’t feel like writing their own. It basically allows you to select an EEPROM address and specify a payload to be written to that particular address. I only needed access to the first 100 or so bytes, so I didn’t bother implementing the full 16 bit address word functionality into the section of code that handles serial communication. You should be able to add that in without too much trouble though, since both readEEPROM() and writeEEPROM() fully support 16 bit addresses. (change the int address to unsigned int address if you are using larger EEPROMs and need addresses larger than 32767)

#include <Wire.h>
#define EEPROM_ADDR 0x57
#define WAIT_FOR_SERIAL(x) while(Serial.available()<x)

void writeEEPROM(uint8_t _data, int address) {
  Wire.beginTransmission(EEPROM_ADDR);
  Wire.write(address >> 8);
  Wire.write(address & 0xff);
  Wire.write(_data);
  delay(10); //chuck in a tWR
  Wire.endTransmission();
  return;
}

uint8_t readEEPROM(int address) {
  Wire.beginTransmission(EEPROM_ADDR);
  Wire.write(address >> 8);
  Wire.write(address & 0xff);
  Wire.endTransmission();

  Wire.requestFrom(EEPROM_ADDR, 1);
  return (Wire.read());
}



void setup() {
  Serial.begin(9600);

  Wire.begin();
}

void loop() {
  
  while(Serial.available() > 0){
    int addr = Serial.read();
    Serial.println("Insert Data");
    WAIT_FOR_SERIAL(1); //wait for payload
    uint8_t payload = Serial.read();
    Serial.println(payload);
    writeEEPROM(payload, addr);
    delay(100);
    uint8_t readback = readEEPROM(addr);
    Serial.println(readback);
    //wait for input
  }
  

}

Leave a Comment

Your email address will not be published. Required fields are marked *