Sunday, February 28, 2010

AVR: storing a 2d array in PROGMEM

I've just been fangling with a UV Painter project (row of LEDs to 'paint' on a glow-in-the-dark-wall). I quickly ran out of RAM when adding patterns to the system and learned how to add variables to the Flash program memory instead. Pretty simple and very useful:


#include <avr/pgmspace.h>

const uint8_t mCylonScan[10][N_LED] PROGMEM = {
{255,0,0,0,0,0},
{0,255,0,0,0,0},
{0,0,255,0,0,0},
{0,0,0,255,0,0},
{0,0,0,0,255,0},
{0,0,0,0,0,255},
{0,0,0,0,255,0},
{0,0,0,255,0,0},
{0,0,255,0,0,0},
{0,255,0,0,0,0}
};

Then to access the data you just do the following (where 'i' and 'j' are loop variables):

data = pgm_read_byte(&(mCylonScan[i][j]));


See the AVR libc docs for more details.

4 comments:

  1. You just saved me......thanks a lot

    ReplyDelete
  2. how to pass this array to a function and use there?
    thanks.

    ReplyDelete
    Replies
    1. This is just standard C. I'd suggest passing it as a pointer. Here's a tutorial on passing arrays to functions in C:

      http://www.tutorialspoint.com/cprogramming/c_passing_arrays_to_functions.htm

      Delete