Cara simpan data string ke EEPROM untuk ESP8266
Author
Cak Lihat
Date
15 Jul 2019
Views
137

The arduino and ESP8266 EEPROM library only provides functions to read and write one byte at a time from the internal EEPROM. Note that EEPROM has limited number of writes.

In this tutorial I will provide some functions to store string to EEPROM and Read back to String variable. String is basically character array terminated with null (0x00).

The microcontroller on the Arduino and Genuino AVR based board has EEPROM: memory whose values are kept when the board is turned off (like a tiny hard drive). EEPROM library enables you to read and write those bytes only.

Spesifikasi EEPROM dari beberapa board yang support arduino :

  • 1024 bytes on the ATmega328P,
  • 512 bytes on the ATmega168 and ATmega8,
  • 4 KB (4096 bytes) on the ATmega1280 and ATmega2560.
  • The Arduino and Genuino 101 boards have an emulated EEPROM space of 1024 bytes.
#include <EEPROM.h>
 
void writeString(char add,String data);
String read_String(char add);
 
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  EEPROM.begin(512);
  String data = "Hello World";
 
  Serial.print("Writing Data:");
  Serial.println(data);
 
  writeString(10, data);  //Address 10 and String type data
  delay(10);
}
 
void loop() {
  // put your main code here, to run repeatedly:
  String recivedData;
  recivedData = read_String(10);
  Serial.print("Read Data:");
  Serial.println(recivedData);
  delay(1000);
}
 
void writeString(char add,String data)
{
  int _size = data.length();
  int i;
  for(i=0;i<_size;i++)
  {
    EEPROM.write(add+i,data[i]);
  }
  EEPROM.write(add+_size,'\0');   //Add termination null character for String Data
  EEPROM.commit();
}
 
 
String read_String(char add)
{
  int i;
  char data[100]; //Max 100 Bytes
  int len=0;
  unsigned char k;
  k=EEPROM.read(add);
  while(k != '\0' && len<500)   //Read until null character
  {    
    k=EEPROM.read(add+len);
    data[len]=k;
    len++;
  }
  data[len]='\0';
  return String(data);
}




0 Comments

We'll never share your email with anyone else.