Memory (Flash and SRAM) optimisations in Arduino
I recently build a rather large project using Arduino and found myself running out of program space...
not SRAM, didnt have any sporadic restarts or "hangs" or glitchy behavior,
" 33912 bytes (of a 28672 byte maximum) , sketch too big "
I didn't see that coming at all.. mostly because i was doing 2 separate parts of the application and testing them separately, I then combined them and this happened...
so here are a few things one can do if you run out of space in Arduino.
don't use floating point math if you don't need to, avoid datatypes like "double" and "float" - in arduino they are the same thing...
The reason is that the Atmega 8 microcontroller does not have a floating point unit... so it is all implemented in software libraries, eating about 2 kbytes of program memory ( FLASH ). So I removed any floating point operations I Had and cleaned up some "if - else" statement and recompiled...
" 31930 bytes (of a 28672 byte maximum) sketch too big "
that's just over 2K of memory, but still too large..
another thing one can do is to tidy up your code, look for places where you do things that are redundant redundant like having multiple "Serial.print("some text"); statements where 1 would be fine.
this is a silly example:
switch(inputValue) { case '1' : Serial.println("The value was 1"); break; case '2' : Serial.println("The value was 2"); break; case '3' : Serial.println("The value was 3"); break; default: break; }
Can be Replaced by something like :
Serial.print("The value was ");
Serial.print(inputValue);
this was a silly example, but its the most simplified way of seeing the error that one can make and how often one has a lot of redundant code... which adds up eventually.
I'll do more posts about memory optimisations like :
using the correct data types ( even in the arduino core files )
avoid too many global variables
removing unused code / things stored in memory that aren't used
removing data that is initialised to a value just be changed again
direct port manipulations
using "inline and "static" functions
smaller buffers for things ( if you know how much data you expect from an SPI or I2C device)
pointers ( this goes with data structures )
a lot of the things were from here