2016/05/02

Writing String To ATMEL AT24C02 256 Bytes (2K bits) I2C EEPROM

Sometimes I need to store default data. Storing the data in external I2C EEPROM is suitable than in ATMEGA328P built-in EEPROM when you want to change the data values.

For ATMEGA328P built-in EEPROM, you have to upload a sketch to change the default data and re-upload the sketch for use.

For external I2C EEPROM, you just unplug the IC from IC socket and replace a new one with default data you need. Uploading sketches are not needed. And the chip is cheap, it costs only 0.03 USD.

Wiring

1. AT24C02.P01 - GND
2. AT24C02.P02 - GND
3. AT24C02.P03 - GND
4. AT24C02.P04 - GND
5. AT24C02.P05 - ArduinoUno.A4
6. AT24C02.P06 - ArduinoUno.A5
7. AT24C02.P07 - GND
8. AT24C02.P08 - 5V

Sketch

// Modified by Befun Hung on May 2, 2016 
// For writing string to ATMEL AT24C02 I2C EEPROM from address 0 once and display all values in the EEPROM on serial monitor once
// The ATMEL AT24C02 I2C EEPROM with 256 bytes (2K bits) need only one byte for addressing is suitable for storing short text message such as id and ip configuration
//
// ** Original comment in simplified Chinese, the original sketch write in EEPROM numbers equal to it's address, read the values and display on serial monitor repeatedly 
//直接给你个24c02简单的程序吧  不用附加库  别的带附加库也可以
//byte 换为int也行, 多数据,大于255的数据自己for循环存吧,double float论坛有教程
#include <Wire.h>

#define colPerLine 8
// define idLen according the length of id value needed
#define idLen 8
char id[idLen+1] = "25613804";


int i = 0;
int val; 

void Writebyte(byte DeviceAddress, byte DataAddress, byte Data)
{
  int rData = Data;
  Wire.beginTransmission(DeviceAddress);
  Wire.write(DataAddress);
  Wire.write(rData);
  Wire.endTransmission();
  delay(10);
}

byte Readbyte(int DeviceAddress, byte DataAddress)
{
  byte rdata = 0xFF;
  Wire.beginTransmission(DeviceAddress);
  Wire.write(DataAddress);
  Wire.endTransmission();
  Wire.requestFrom(DeviceAddress, 1);
  delay(10);
  if (Wire.available())
  {
    rdata = Wire.read();
  }
  delay(10);
  return rdata;
}

void setup()
{
  Wire.begin();
  Serial.begin(115200);
  
  for (i=0;i<256;i++) {
    if (i< idLen) {
       Writebyte(0x50,i,id[i]);
    }
    else {
      // comment out the following line if values in the address greater than idLen not to be overrided with 0
      Writebyte(0x50,i,0);
    }
  }
  
  for (i=0;i<256;i++) {
    if ((i%colPerLine) == 0) Serial.println("");
    val = Readbyte(0x50,i);
    Serial.print(val);
    Serial.print(" ");
  }
}

void loop()
{
    // if (i > 0xFF)
    // {
    //   i = 0x00;
    // }
    // Writebyte(0x50, i, i);
    // val = Readbyte(0x50, i);
    // i++;
    // Serial.print(val);
    // Serial.print(" ");
    // if ((i%8) == 0) Serial.println("");
}

No comments:

Post a Comment