Arduino Due randomly slows down, serial communications stops I've got an Arduino Due connected to a Raspberry Pi via Serial3. The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours. Using an oscilloscope, I can see that the Pi keeps transmitting to the Due, but there is no response from the Due. I'm also getting the Due to echo everything it gets from the Pi to Serial, which is connected to my PC. I can see that the Due will stop echoing characters mid way through receiving a message from the Pi.

I then set one of the pins as an output and just keep toggling that regularly. When the Due is waiting for data from the Pi, this signal has a frequency of about 100Hz, i.e. a period of 10ms. I have a counter that goes from 0 to 1000 to control this frequency somewhat. When this error happens and communications stops, I can see that the pulses now have a period of 2.14 seconds, i.e. 214 times slower.

I'm using Arduino-MemoryFree to check for memory leaks but I haven't found any problems yet and I don't seem to be running out of memory. In case it matters, I'm also using the ArduinoJson library. Arduino IDE version is 1.6.7, I've updated the Arduino SAM Boards package to version 1.6.9 (problem was present before the update as well).

Could someone please advise me on what could be causing this slow down?
The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours.


Here is the typical manifestation of heap fragmentation in an Arduino sketch.

Solution:


Remove as many Strings as possible and replace them with char[]
Use a StaticJsonBuffer instead of a DynamicJsonBuffer


If you remove all the Strings and use a StaticJsonBuffer, your program will run without any heap. No heap, no fragmentation! Not only it will be more reliable, it will also be smaller and faster.

If you must use String, then call String::reserve() to make sure the size is the same at each iteration. Indeed, repeated allocation of the same size doesn't increase fragmentation.