Putting data in flash on the Arduino

From Wikiid
Revision as of 18:47, 1 January 2009 by SteveBaker (Talk | contribs) (New page: 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 == ...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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:

 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!