I am having trouble reliably reading a json string in my Arduino Mega. I have print statements in my source Python that output the expected data every time: the python code I am using the UART Tx/RX on both the Pi and Arduino
if(updateArduino):
print('update Arduino')
ampJson = json.dumps({"ms": curent_matchState,"ac": amplificationCount,"co": cooperationStatus,"as": amplificationSecRemaining})
print(f'Info: sent to Arduino {ampJson}')
usb_connection.write(bytes(ampJson, 'utf-8'))
updateArduino = False
That outputs:
Info: sent to Arduino {"ms": "6", "ac": 0, "co": false, "as": 0}
on the Arduino side if all I do is monitor the Serial1 port i get reliable JSON packet from the code here
void loop(){
long int currentTime = millis();
// Check if the other Arduino is transmitting
if (Serial1.available())
{
// Allocate the JSON document
// This one must be bigger than the sender's because it must store the strings
StaticJsonDocument<500> doc;
// Read the JSON document from the "link" serial port
DeserializationError err = deserializeJson(doc, Serial1);
if (err == DeserializationError::Ok)
{
// Print the values
// (we must use as<T>() to resolve the ambiguity)
String output;
serializeJson(doc, output);
Serial.println("From the Debuger");
Serial.print("size ");
Serial.println(doc.size());
Serial.println(output);
Serial.print("Bytes ");
Serial.println(output.length());
matchState_int = doc["MState"].as<int>();
Serial.print("MState : ");
Serial.println(matchState_int);
}
else
{
// Print error to the "debug" serial port
Serial.print("deserializeJson() returned ");
Serial.println(err.c_str());
// Flush all bytes in the "link" serial port buffer
while (Serial1.available() > 0)
Serial1.read();
}
}
}
Outputs Reliably: `13:22:08.284 -> From the Debuger
13:22:08.284 -> size 4
13:22:08.284 -> {"ms":"6","ac":0,"co":false,"as":0}
13:22:08.284 -> Bytes 35
13:22:08.284 -> MState : 6
13:22:18.271 -> From the Debuger
13:22:18.271 -> size 4
13:22:18.271 -> {"ms":"6","ac":0,"co":false,"as":0}
13:22:18.271 -> Bytes 35
13:22:18.271 -> MState : 6 `
HERE STARTS THE ISSUE When I add the remainder of the code to my Arduino (That takes time to process I start to get errors in the JSON object. When I had longer key values it steamed to always corrupt the first key "MS" I get a lot of
`13:33:25.945 -> deserializeJson() returned InvalidInput
13:33:25.945 -> deserializeJson() returned InvalidInput
13:33:26.974 -> deserializeJson() returned IncompleteInput
`
I'm assuming I have filled the buffer and am having alot of over flow. How do I or should I terminate the JSON string and purge the buffer for new data?
Like I said above I have tried to test just reading and it seems to work