I experience some strange behaviour when reading data from the eeprom.
My function "print_string_from_eeprom(start_address)" reads characters from the eeprom and stores them in a buffer until the NULL character is found. Then the buffer is printed.
When the Arduino Uno reads and prints the characters one byte at a time, the output is correct
" abcdef hijklmn".
But when I use my function two errors occur:
- Some characters are missing / skipped.
- The 0 is not always recognized.
#include <EEPROM.h>
void print_string_from_eeprom(int initial_start_address){
//continue reading from initial_start_address until '\0' or end of memory
char current_char;
bool continue_read = 1;
int current_address = initial_start_address;
while(continue_read){
const uint8_t buffer_size = 20;
char buffer[buffer_size] = {0};
for(int i = 0; i< buffer_size; i++){
current_address = current_address + i;
//Abort if out of memory area
if (current_address == EEPROM.length()){
Serial.print("OUT OF BOUND");
continue_read = 0;
break;
}
current_char = EEPROM.read(current_address);
delay(100);
if (current_char == NULL) {
continue_read = 0;
//Serial.print("NULL");
break;
}
buffer[i] = current_char;
}
Serial.print(">");
Serial.print(buffer);Serial.print("<");
}
}
void setup(){
Serial.begin(9600);
EEPROM.update(0, 0);
EEPROM.update(1, 0);
EEPROM.update(2, 'a');
EEPROM.update(3, 'b');
EEPROM.update(4, 'c');
EEPROM.update(5, 'd');
EEPROM.update(6, 'e');
EEPROM.update(7, 'f');
EEPROM.update(8, 0);
EEPROM.update(9, 'h');
EEPROM.update(10, 'i');
EEPROM.update(11, 'j');
EEPROM.update(12, 'k');
EEPROM.update(13, 'l');
EEPROM.update(14, 'm');
EEPROM.update(15, 'n');
EEPROM.update(16, NULL);
for (int i = 0; i<17; i++){
Serial.print((char)EEPROM[i]); //gives correct output " abcdef hijklmn"
}
Serial.println();
delay(1000);
for (int i = 0; i<12; i++){
Serial.print("from "); Serial.print(i); Serial.print(": ");
print_string_from_eeprom(i); //here the wrong output occurs
Serial.println();
delay(1000);
}
}
void loop(){}
The bytewise read / print command gives
abcdef hijklmn < //correct
But my function (starting at address ... returns):
from 0: >< //correct
from 1: >< //correct
from 2: >abd< // should be "abcdef"
from 3: >bcehl< // should be "bcdef"
from 4: >cdfim< //should be "cdef"
from 5: >de< // should be "def"
from 6: >efhk< // should be "ef"
from 7: >f< //correct
from 8: >< //correct
from 9: >hik< /should be "hijklmn"
from 10: >ijl< //should be "ijklmn"
from 11: >jkm< //should be "jklmn"
I have been looking over my code again and again, without spotting the flaw.
Can someone please confirm this output and check the code?