Program freezes after a while

robtillaart:
Possible deadlock (causes a freezer) found: message_length is a byte and if messagelength == 255 this loop will never stop.

Thanks for spotting that. However it can't be the cause of the freezes because I am never sending any message longer than 5 bytes.

PeterH:

giorgisp:
if I use a 5V 2A AC adapter or a 5V usb charger I've got, the microcontroller eventually freezes after some commands. So it's something related to power supply

Maybe if your power supply is not producing very clean, well regulated DC then the Arduino could suffering from spikes or out-of-spec voltages which are provoking logic faults. Presumably you're bypassing the onboard regulator, so whatever your wallwart produces goes direct to the processor, noise and all. The current ratings you mention make me suspect these are intended as battery chargers rather than to directly power digital devices, so they may not be well regulated and smoothed.

I also tried it powering it from my laptop's usb port through the programmer (while it was running on battery) and it still froze after some commands. It doesn't freeze if I don't send any commands. I can leave it powered from the ac adapter overnight and it is still running the next morning until I send some commands and it freezes again.

My hardware design indeed feeds the input power directly to the microcontroller. What could I do to filter the power before it reaches the circuit?

I really don't know what to do. It seems very unlikely that this is a software error. I forgot to mention that I'm using the atmega's internal oscillator to save space. However, the master board which sends the commands uses an external crystal oscillator and it freezes too sometimes after sending a lot of commands.

Update: I found some power regulator boards I had purchased from ebay (these ones: http://www.ebay.com/itm/271143310513) with a 12v input and 5/3.3v 3A output. It seems they use good regulators and have capacitors and coils and other filtering components, so I am going to wire up one of them, power the controller board with it and see what happens.