I am sending serialized json data from my arduino to a program that is running in C++ but am getting some incomplete data. I was using a temporary fix checking whether the object!= NULL which was working but meant that I was losing some data.
The C++ code is using the serialPort library and my DATA_LENGTH is 64.
char receivedData[DATA_LENGTH];
if (arduino->isConnected()) {
int hasRead = arduino->readSerialPort(receivedData, DATA_LENGTH);
if (hasRead) {
DEBUG(receivedData);
json_t* object = json_loads(receivedData, DATA_LENGTH, NULL);
//if (object != NULL) {
json_t* value = json_object_get(object, "v");
The arduino program is sending the data of a 10k pot. Here is my loop()
I don't see anything missing. Sometimes your receive a single JSON package in two chunks. You have to know where the begin and where the end of the data package is.
One way to do that is to read every single received byte into a buffer. Check the buffer to see if the data is complete.
Thank you. So because I know that I'm only sending a single object I can append the chunks to a separate buffer then check if the last character of the buffer is "}" ?
Yes, and you can start reading when a '{' is received.
When you try to read the full DATA_LENGTH at once, that data might not be complete and might still be coming in. There could also be a synchronization problem (reading the last part of a package and the first part of the next package) because once you are out of sync, there is no code to get in sync again.
I don't know what those functions do and how large the buffers are. You could print the 'receivedData' after the call to readSerialPort() ?
Is the readSerialPort() your own function ? How does it know when to stop reading ? Does it have a timeout ? Does it always add a zero-terminator at the end ?
At first glance I think that the library is not fail safe.
A memset() fills the buffer with zeros, hopefully one of those zeros will become a zero-terminator for the data. If there is enough incoming data to fill the whole buffer, then the buffer will be filled up to the very last byte and then there is no zero-terminator at the end.
Suppose you read a lot of rubbish because of some bug and all 64 bytes will be filled, then your code will fail.
Let's assume that your 64 byte buffer is large enough for the small JSON data.
Then it is possible that not everything is read. You could print the 'hasRead' value.
It is long time ago that I used Windows/Microsoft programming. Can you debug it or print variables right after the readSerialPort() call ?
There is probably a bug that causes the first character and the last-1 to be wrong, but I don't see that bug.
Feel like I might be doing something wrong when I'm trying to append to the fullObject buffer as It looks like it is being read in the correct order as it looks fine when I print the 2 chunks from receivedData in the first screen shot.