Arduino reading json from EEPROM / converting uint8_t to char

天涯浪子 提交于 2019-12-24 08:29:41

问题


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.



来源:https://stackoverflow.com/questions/39169973/arduino-reading-json-from-eeprom-converting-uint8-t-to-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!