I think this is probably a generic question about my misunderstanding of references, but it's specifically come up while using the ArduinoJson library.
I got my program succesfully reading JSON from an external source, using the ArduinoJson library to parse it, converting data into the form I need it, and so on.
Having got it roughly working, I then started cleaning it up and moved a bit of code into a function so that I could call it in two places.
The critical piece is a loop over a JsonArray. Originally it was inline in the function that had parsed the JSON data, i.e. (omitting various error checking):
float fWidth;
DeserializationError error = deserializeJson(doc, jsonText);
...
JsonArray aDims = doc["dimensionsList"].as<JsonArray>();
...
for (JsonObject repo : aDims) {
fWidth = repo["width"];
Serial.println(fWidth);
}
... which works fine.
Then I attempted to move the processing of the elements of the array into a function, and it crashes as soon as it tries to access one of the elements of the JsonObject:
DeserializationError error = deserializeJson(doc, jsonText);
...
JsonArray aDims = doc["dimensionsList"].as<JsonArray>();
...
for (JsonObject repo : aDims) {
printWidth(repo);
}
...
void printWidth(JsonObject jElement)
{
float fWidth;
fWidth = jElement["width"]; // crashes on this line
Serial.println(fWidth);
}
Evidently there is an issue with how I pass the iterator JsonObject into the function - or how I then access the elements of it.
I've read @BenoitB's excellent book, with the very helpful "missing C++ course" chapter; but I didn't see anything which would suggest that this shouldn't work. I've also in desperation tried all the variations of syntax I could imagine, but none worked. I also, since (in the actual code as opposed to the above cut-down one) the secondary function doesn't need to change the values in the JsonObject, tried declaring it as const in the secondary function; no joy.
I don't see why it wouldn't be possible to pass a reference into a function, and then use it in this way... am I wrong? And if not, what am I doing wrong in this syntax?