CyrielN
CyrielN

Reputation: 99

C++/Arduino Passing pointer to 2D array stored in PROGMEM

I have several const int 2D arrays globally stored in PROGMEM. for example:

const int image1[][17]PROGMEM = {
  {1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0},
  {1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0},
  {1,1,1,0,0,0,0,0,1,1,1,1,0,0,0,0,0},
  {1,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0},
  {1,1,1,0,0,0,1,1,1,0,0,1,1,1,1,0,0}
}

I would like to read out this 2d image array in a function. Which image to read out should be specified in the argument.

void printImage(image)
{
  // do something with element i,j of image
  pgm_read_byte(image[i][j])
}

I am not very expierenced with the use of pointers etc. but I know that's the way to do it. Can you show me how to make it work?

EDIT1: How I do it now (it works, but it is not elegant); I have the function printImage1() without any arguments, and in the body function I use:

pgm_read_byte(&image1[i][j])

to read out image1. For image2, image3 etc. I copy the function printImage1 and change imgage1 from above to image2, image3 etc. This is redundant programming thats why I want to specify the image in the argumant using only one function printImage.

Upvotes: 1

Views: 1719

Answers (1)

Wintermute
Wintermute

Reputation: 44063

pgm_read_byte takes the address of the byte you want to read. You could use

pgm_read_byte(&image[i][j])

or

pgm_read_byte(image[i] + j)

Note, however, that it is unusual to use pgm_read_byte on an array of int (which are 2 bytes wide on AVR). You should probably make image1 a 2D array of uint8_t or use pgm_read_word.

Upvotes: 0

Related Questions