Reputation: 21
I'm having a problem passing data to EEPROM. It seemed to be not accepting a char variable. I'm doing exactly what is told here: https://www.arduino.cc/en/Reference/EEPROMPut
So my this is my Object Structure
struct DeviceDataObject {
bool flag;
char data[20];
char data2[20];
int rate1;
int rate2;
int rate3;
};
So as I test with:
int RATES[3] = {300, 1500, 3600};
DeviceDataObject new_data = {true, "Data1Sample", "Sample2", RATES[0], RATES[1], RATES[2]};
WRITE_Device(new_data);
Here's my writing function
void WRITE_Device(DeviceDataObject data) {
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
int eeAddress = 0;
float f = 123.456f; //Variable to store in EEPROM.
EEPROM.put(eeAddress, f);
eeAddress += sizeof(float); //Move address to the next byte after float 'f'.
EEPROM.put(eeAddress, data);
//Serial.println("Memory Data Updated");
}
Everything seemed to be OK. But if I replace "Data1Sample"
and "Sample2"
with a variable, EEPROM's data seemed to be changed in incorrectly.
void ChangeValue(String value) {
int RATES[3] = {300, 1500, 3600};
char charBuf[20];
value.toCharArray(charBuf, 20); //Convert to char
DeviceDataObject new_data = {true, "", {charBuf}, RATES[0], RATES[1], RATES[2]}
WRITE_Device(new_data);
}
What could be the mistake?
Upvotes: 0
Views: 1890
Reputation: 173
A somewhat long-winded approach would be to write each element of the structure to EEPROM individually. The code would look something like this and should allow you to isolate any issues more effectively.
ee_address = 0;
EEPROM.put(ee_address, new_data.flag);
ee_address += sizeof(new_data.flag); // Update address to store next variable
EEPROM.put(ee_address, new_data.data);
ee_address += sizeof(new_data.data);
EEPROM.put(ee_address, new_data.data2);
ee_address += sizeof(rawdata.data2);
EEPROM.put(ee_address, new_data.rate1);
ee_address += sizeof(new_data.rate1);
EEPROM.put(ee_address, new_data.rate2);
ee_address += sizeof(new_data.rate2);
EEPROM.put(ee_address, new_data.rate3);
ee_address += sizeof(rawdata.rate3);
This will make it easier to troubleshoot whether variables are not being written to EEPROM correctly or whether the issue stems from something else.
This is the approach I typically take when storing structures which I have defined to the EEPROM, as it gives more control when retrieving this information from the EEPROM at a later point.
I'll be the first to admit this is perhaps not the most elegant solution, but it should help address your issues.
Upvotes: 0
Reputation: 71
Looks like a pointer problem, try this
void ChangeValue(String value) {
int RATES[3] = {300, 1500, 3600};
DeviceDataObject new_data = {true, "", "", RATES[0], RATES[1], RATES[2]}
value.toCharArray(new_data.data2, 20); //Convert to char
WRITE_Device(new_data);
}
(you were creating a string where the first character was the pointer to your stack variable charBuf, rather than copying the string)
Upvotes: 0