Hello!
I am old but an Arduino beginner.
I wrote a header file to allow the insertion and search in EEPROM of values using a numeric key or a char array key. The key is written together with the value in a B-Tree structure. In this way, bytes are wasted, but in some situations it may be useful.
Char arrays are stored in the EEPROM up to the value '\ 0' even if they are longer.
the main commands are:
DS_put (key, value); Writes a key / value pair
DS_get (key, value); reads the value by supplying the key
the key can be a 16-bit integer or a char array
the value must be a char array
DS_format (); It deletes the EEPROM and writes the first usable address to position 0.
I provide below a test code and enclose the header file.
#include <stdio.h>
#include "DS_EEProm_New.h"
void setup() {
Serial.begin(9600);
}
void ReadStringFromSerial(char searchedString[]){
while(!Serial.available()){delay(20);}
byte j=0;
while(Serial.available())
{
searchedString[j] = Serial.read();
++j;
searchedString[j] = '\0';
}
//return searchedString;
}
void loop() {
char searchedString[100];
char keyString[50];
char valueString[100];
char command[5];
Serial.println("-----------------Insert command-----------------");
Serial.println("Format EEPROM -----> f");
Serial.println("List EEPROM byte -----> l");
Serial.println("Write int Key int and *char Value -----> wi");
Serial.println("Write *char Key int and *char Value -----> ws");
Serial.println("Search Value with int Key -----> ri");
Serial.println("Search Value with *char Key -----> rs");
ReadStringFromSerial(command);
if (strcmp(command,"f")==0)
{
Serial.println("Format begin");
DS_format();
Serial.println("Format end");
}
else if (strcmp(command,"l")==0)
{
uint8_t val;
for (int cont=0; cont<100; cont++)
{
val=eeprom_read_byte(cont);
Serial.print(cont,DEC);
Serial.print("-->");
Serial.println(val,DEC);
}
}
else if (strcmp(command,"wi")==0)
{
Serial.println("Insert Key");
ReadStringFromSerial(keyString);
Serial.println("Insert Value");
ReadStringFromSerial(valueString);
DS_put(atoi(keyString),valueString);
}
else if (strcmp(command,"ws")==0)
{
Serial.println("Insert Key");
ReadStringFromSerial(keyString);
Serial.println("Insert Value");
ReadStringFromSerial(valueString);
DS_put(keyString,valueString);
}
else if (strcmp(command,"ri")==0)
{
Serial.println("Insert Key");
ReadStringFromSerial(keyString);
if (DS_get(atoi(keyString),searchedString)==1)
{
Serial.print(atoi(keyString));
Serial.print(" ------------> ");
Serial.println(searchedString);
}
}
else if (strcmp(command,"rs")==0)
{
Serial.println("Insert Key");
ReadStringFromSerial(keyString);
if (DS_get(keyString,searchedString)==1)
{
Serial.print(keyString);
Serial.print(" ------------> ");
Serial.println(searchedString);
}
}
delay(1000);
}
DS_EEProm_New.h (8.28 KB)