úterý 26. ledna 2016

Why is serial output of my Arduino garbled?

Ugly Arduino output

I spent few hours to solve garbled serial output produced by my Arduino (Uno, Nano, doesn't matter). All of a sudden the serial output looked ugly:


I tried to revert last lines I added to the code. Sometimes it helped, sometimes little bit and there was no one single row which was causing it... However, the solution was very easy. As I was adding code to just testing sketch I didn't care about best programming practices and I wasted whole my RAM memory .... 
Problem is, that pretty all serial communications libraries are using dynamic buffers, which could be pretty demanding. In my case, when I compiled and started the code, just 57 bytes left in the memory. When the communication channel was busy the Arduino simply ran out of memory.

So what I learned? 

Every time you can use F() to store string in program memory, even for just test projects. Other memory saving techniques can be found on google.. :)

use following function to check amount of available memory:

int freeRam() {
  extern int __heap_start,*__brkval;
  int v;
  return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int) __brkval);
}