/* Ejemplo EEPROM
* Autor: kans
* Fecha: 05/03/2008
*/
#include <Wire.h> //libreria I2C
//Las siguientes funciones para lectura y escritura en una EEPROM se encuentran en el wiki de Arduino: http://www.arduino.cc/playground/Code/I2CEEPROM
void i2c_eeprom_write_byte( int deviceaddress, unsigned int eeaddress, byte data ) {
int rdata = data;
Wire.beginTransmission(deviceaddress);
Wire.send((int)(eeaddress >> 8)); // MSB
Wire.send((int)(eeaddress & 0xFF)); // LSB
Wire.send(rdata);
Wire.endTransmission();
}
// WARNING: address is a page address, 6-bit end will wrap around
// also, data can be maximum of about 30 bytes, because the Wire library has a buffer of 32 bytes
void i2c_eeprom_write_page( int deviceaddress, unsigned int eeaddresspage, byte* data, byte length ) {
Wire.beginTransmission(deviceaddress);
Wire.send((int)(eeaddresspage >> 8)); // MSB
Wire.send((int)(eeaddresspage & 0xFF)); // LSB
byte c;
for ( c = 0; c < length; c++)
Wire.send(data[c]);
Wire.endTransmission();
}
byte i2c_eeprom_read_byte( int deviceaddress, unsigned int eeaddress ) {
byte rdata = 0xFF;
Wire.beginTransmission(deviceaddress);
Wire.send((int)(eeaddress >> 8)); // MSB
Wire.send((int)(eeaddress & 0xFF)); // LSB
Wire.endTransmission();
Wire.requestFrom(deviceaddress,1);
if (Wire.available()) rdata = Wire.receive();
return rdata;
}
// maybe let's not read more than 30 or 32 bytes at a time!
void i2c_eeprom_read_buffer( int deviceaddress, unsigned int eeaddress, byte *buffer, int length ) {
Wire.beginTransmission(deviceaddress);
Wire.send((int)(eeaddress >> 8)); // MSB
Wire.send((int)(eeaddress & 0xFF)); // LSB
Wire.endTransmission();
Wire.requestFrom(deviceaddress,length);
int c = 0;
for ( c = 0; c < length; c++ )
if (Wire.available()) buffer[c] = Wire.receive();
}
void setup() {
char cadena[] = "hola mundo desde una eeprom"; //cadena a escribir
Wire.begin(); //es obligatorio inicializar la conexion
Serial.begin(9600);
i2c_eeprom_write_page(0x50, 0, (byte *)cadena, sizeof(cadena)); //escribir la cadena al principio de la EEPROM; comentar esta linea para probar que la memoria es no volatil
delay(10); //pequeña pausa despues de escribir en la memoria
}
void loop() {
int addr=0; //direccion a leer
byte b = i2c_eeprom_read_byte(0x50, 0); //acceso a la primera posicion de memoria
while (b!=0) {
Serial.print((char)b); //enviar al ordenador
addr++; //siguiente direccion
b = i2c_eeprom_read_byte(0x50, addr); //acceso a posicion de memoria
}
Serial.println();
delay(2000);
}