Putting data in flash on the Arduino

From Wikiid
Jump to: navigation, search

Since main RAM memory is very limited on the Arduino, you need to put const data into flash memory wherever possible.

There is a necessary trick to doing this:

Declaring the data

The 'PROGMEM' macro places an object into program memory (ie flash):

 #include <avr/pgmspace.h>
 const char myArray [] PROGMEM = { ... } ;

Accessing the data

But to access the data, you have to use a special set of functions:

 #include <avr/pgmspace.h>
 pgm_read_byte ( & myArray [ 10 ] ) ;

...there is also 'pgm_read_word' for 16 bit data and 'pgm_read_dword' for 32 bits. This only works for 16 bit addresses - but until we have Arduino's with more than 64kb of flash, this is not a problem. For machines with more, there is pgm_read_xxx_far and pgm_read_xxx_near for 32 and 16 bit addresses. You really need to cast the results of the pgm_read_* routines because they are implemented in machine-code and the return type is kinda ill-defined!

String functions

Since it's very common to want to place string constants in program memory - there are versions of all of the standard string library functions that work on program-space data. These have an '_P' suffix (hence: strcpy_P, memcmp_P, etc).

Wikiid Pages relating to Arduino (edit)
Command line Arduino
Startup code for Arduino
Low level functions for Arduino
Putting data in flash on the Arduino
External resources for Arduino
Board schematics for Arduino
Misc notes: Circuit notes, Music notes, Stepper motors