Nokia 6110 Part 4 – Programming

This is a four part series:

I previously talked about the code for the display driver, and the code for the snake AI algorithm, but here I want to just tie it all together.

I used the arduino tools, setup like so:

arduino options cpu arduino options board

I initially made a mistake and used the default 5V option with the 3V board.  It uploaded correctly, but the serial output was at half the expected speed.  This is because the 5V board runs at 16mhz, but the 3.3V board runs at 8Mhz. (As a side note, I searched for the particle AVR chip and it’s actually rated at 20mhz and 10mhz respectively.  I wonder why the Arduino underclocks the processor?  As a second side note, for fun I tested a 5V board at 16mhz but actually fed it 3.3V and amazingly it worked.  Obviously reliability is probably an issue, but the tolerance for low voltage is well outside the official specs, so in pinch you can really abuse this hardware.  I got it down to 3.1V before the 5V board gave up).

Programming for the PC

I wrote the code such that the arduino-specific code was as minimal as possible, and kept in .ino files.  And the rest of the code in .cpp files.  The result was that I could do almost all the development and debugging for the PC.

Although this was slightly more work (e.g. I had to write an ncurses output), it was very much worth it.  I compiled the program with:

gcc -fno-omit-frame-pointer -fsanitize=address \
    -Wno-char-subscripts -g -Wall snake.cpp \
    -o snake -lncurses

The sanitize=address option is new to GCC 4.8.0 and is extremely cool.  It’s a memory error checker and it saved my bacon several times.  For me, it has replaced valgrind’s memchecker tool.

Monitoring memory usage

I needed to be aware of every byte of memory that I used throughout the project, and to compare my theoretical counting against actual usage I used a pretty neat trick that I found on the internet:

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

This function returns the amount of free memory by taking the current stack position (since v is on the stack), and taking the difference to the current heap position.  This works because on arduino the heap and stack grow towards each other, like this:

Final product

Final product uses 1.4KB out of the 2KB of memory available.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s