Open interactive-matter opened 13 years ago
aJson.print() returns a dynamically allocated string, it is your responsibility to call free() on the pointer when you are done with it, so you cannot just directly pass the return value to Serial.print(). Note that with https://github.com/interactive-matter/aJson/pull/29, it will be less hassle to print stuff to streams like this. :-)
Just as an FYI for others who might encounter something that looks similar, the code is malloc'd in the print routine so make sure the pointer you're using is either newly created or freed in advance or weird stuff will happen. =)
code (run on Arduino Uno and JEELINK):
include
aJsonObject* JSONObject; aJsonObject* JSONhostCommand; aJsonObject* JSONhostParameter1; aJsonObject* JSONhostParameter2; aJsonObject* JSONhostLength;
int p1=1000; float p2= 999.99;
void sendFreeRAM(String text) { Serial.print (“[JL: free RAM "); Serial.print (text); Serial.print (": "); Serial.print (freeRAM()); Serial.println (" ]“); }
int freeRAM () { extern int heap_start, *brkval; int v; return (int) &v – (brkval == 0 ? (int) &__heap_start : (int) brkval); }
void setup() { Serial.begin(9600); }
void loop() { aJsonObject *JSONObjectOut; JSONObjectOut=aJson.createObject(); aJson.addNumberToObject(JSONObjectOut, “M”, 5); aJson.addNumberToObject(JSONObjectOut, “P1″, p1); aJson.addNumberToObject(JSONObjectOut, “P2″, p2); aJson.addNumberToObject(JSONObjectOut, “L”, 10.199);
sendFreeRAM(“1: JSON”); Serial.println(aJson.print(JSONObjectOut));
sendFreeRAM(“2: JSON”); aJson.deleteItem(JSONObjectOut);
sendFreeRAM(“3: JSON”); }
All memory alloc function in c/c++ are voodoo to me, so I could not find anything in the code. Do you have an idea?
output here is:
[JL: free RAM 1: JSON: 1330 ] {“M”:5,”P1″:1000,”P2″:999.98999,”L”:10.19900} [JL: free RAM 2: JSON: 1282 ] [JL: free RAM 3: JSON: 1282 ] [JL: free RAM 1: JSON: 1282 ] {“M”:5,”P1″:1000,”P2″:999.98999,”L”:10.19900} [JL: free RAM 2: JSON: 1234 ] [JL: free RAM 3: JSON: 1234 ] [JL: free RAM 1: JSON: 1234 ] {“M”:5,”P1″:1000,”P2″:999.98999,”L”:10.19900} [JL: free RAM 2: JSON: 1186 ] [JL: free RAM 3: JSON: 1186 ] [JL: free RAM 1: JSON: 1186 ] {“M”:5,”P1″:1000,”P2″:999.98999,”L”:10.19900} [JL: free RAM 2: JSON: 1138 ] [JL: free RAM 3: JSON: 1138 ]