Arduino reading json from EEPROM / converting uint

2019-09-05 05:15发布

问题:

I'm using ArduinoJSON to write a couple of data points to my EEPROM on Arduino Uno. I'm running into a problem with getGroundedPR where I need to convert a uint8_t to a char to pass retrieved data into my JSON parser.

This is my first time using EEPROM so I'm willing to bet there's a better way to do this. Should I continue to use JSON or is there a better way? I'm being cautious of the 10k write limit (give or take) on the EEPROM.

the EEPROM read/write is commented out until I have my process nailed down

void IMUController::setGroundedPR(double p, double r) {
  Serial.print("Setting IMU ground: ");

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["pitch"] = p;
  root["roll"] = r;

  root.printTo(Serial);

  char buffer[256];
  root.printTo(buffer, sizeof(buffer));
  Serial.println();

//  EEPROM.write(EEPROM_ADDRESS_IMU_GROUNDED, buffer);
}

double* IMUController::getGroundedPR() {
  double ret[2] = {0, 0};
  StaticJsonBuffer<200> jsonBuffer;
  uint8_t json_saved = EEPROM.read(EEPROM_ADDRESS_IMU_GROUNDED);
  char json[] = "asdf"; // convert json_saved to char here

  JsonObject& root = jsonBuffer.parseObject(json);

  if(!root.success()) {
    // return the result
    ret[0] = (double)root["pitch"];
    ret[1] = (double)root["roll"];
    return ret;
  }

  return ret;
}

回答1:

The EEPROM functions read() and write() only deal with a single character. You need to use put() and get() to deal with arrays.

char buffer[256];
root.printTo(buffer, sizeof(buffer));
EEPROM.put(EEPROM_ADDRESS_IMU_GROUNDED, buffer);

And to read it back:

char json[256];
EEPROM.get(EEPROM_ADDRESS_IMU_GROUNDED, json);
JsonObject& root = jsonBuffer.parseObject(json);

You need to take care with he array sizes though, the EEPROM functions will get and put the number of bytes in the array (256). The string should be null terminated so the extra bytes shouldn't cause a problem.