Wednesday, February 10, 2016

Notes on Arduino Programming

I recently had an epiphany regarding programming the Arduino (see my previous post "The Automenorah Quest" regarding my use of the Arduino board). The first board I acquired used the older Atmel Atmega168 chip, which has 16K of program RAM and 1K of SRAM for variables. I knew that, but did not take into account how little space I had available for modifiable variables, especially for strings. In my programming trials using this platform, I would have some unexpected problems, usually when I was trying to display information through the serial monitor, usually for debugging purposes. The symptom was that suddenly, after adding some new information to be displayed, the display would show gibberish, or at least would display some characters incorrectly. In the most extreme cases, the program would appear to totally fail. I was unable to get it to happen reliably enough to figure out the cause and spent some time doing different trials to try and figure it out.

Eventually, I acquired a new board which had the newer Atmega328, with 32K of program space and 2K of SRAM. This board did not have the same problems with the same code sketches. I finally purchased a new 328 chip for the old board and the problems with that board seemed to be solved.

It was not until recently that the epiphany occurred and it dawned on me that the differences in SRAM were the reason for the failures. As I added more and more character strings to the variables to be displayed on the serial monitor, the failure would eventually happen. I was overrunning the SRAM space with the string variables and causing the crashes. I went looking for information on this and found the method for causing character strings, or any variables, which do not require run-time modification, to be stored in the program space and the code for fetching these variables at run-time.

This solved a whole lot of problems I had been having. Interested parties can find more on the solution here.