Please help - weird issue with PROGMEM

I’m having some issues using PROGMEM with an array of unsigned chars…

template<class T> inline Print &operator <<(Print &obj, T arg) { obj.print(arg); return obj; }


const PROGMEM unsigned char test[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x10};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(57600);

}

void loop() {
  // put your main code here, to run repeatedly:
  int x;
  for (x = 0; x < 11; x++) {
    Serial << x << ":" << test[x] << "\t";
  }
  Serial << "\n";
  delay(2000);
}

This does not work as expected.

0:0	1:0	2:184	3:0	4:0	5:0	6:1	7:0	8:0	9:184	10:184	
0:0	1:0	2:184	3:0	4:0	5:0	6:1	7:0	8:0	9:184	10:184	
0:0	1:0	2:184	3:0	4:0	5:0	6:1	7:0	8:0	9:184	10:184	
0:0	1:0	2:184	3:0	4:0	5:0	6:1	7:0	8:0	9:184	10:184	
0:0	1:0	2:184	3:0	4:0	5:0	6:1	7:0	8:0	9:184	10:184	
0:0	1:0	2:184	3:0	4:0	5:0	6:1	7:0	8:0	9:184	10:184	
0:0	1:0	2:184	3:0	4:0	5:0	6:1	7:0	8:0	9:184	10:184

However, when I remove PROGMEM, it all works… Any ideas?

This is without PROGMEM

0:0	1:1	2:2	3:3	4:4	5:5	6:6	7:7	8:8	9:9	10:16	
0:0	1:1	2:2	3:3	4:4	5:5	6:6	7:7	8:8	9:9	10:16	
0:0	1:1	2:2	3:3	4:4	5:5	6:6	7:7	8:8	9:9	10:16	
0:0	1:1	2:2	3:3	4:4	5:5	6:6	7:7	8:8	9:9	10:16	
0:0	1:1	2:2	3:3	4:4	5:5	6:6	7:7	8:8	9:9	10:16	
0:0	1:1	2:2	3:3	4:4	5:5	6:6	7:7	8:8	9:9	10:16	
0:0	1:1	2:2	3:3	4:4	5:5	6:6	7:7	8:8	9:9	10:16

Can someone please help me?

Forgot to mention, Arduino UNO, 328P

See the example in this link. https://www.arduino.cc/en/Reference/PROGMEM

I can't see anything "weird" - flash memory is a separate address space, but you're treating it as though it were RAM. https://www.arduino.cc/en/Reference/PROGMEM

How am I treating it as RAM? I'm defining it const and only defining it once. Never changing it..

The compiler doesn't automatically adjust for the different way PROGMEM needs to be read. See: http://www.gammon.com.au/progmem

Solved! I figured it out, thanks!

Solution: test is a pointer to program space, pgm_read_byte(test+x)

Thanks for the heads up! I missed that the first 5 times around...

For everyone else who may have this problem, here is the working code for the above example.

template<class T> inline Print &operator <<(Print &obj, T arg) { obj.print(arg); return obj; }


const PROGMEM unsigned char test[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x10};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(57600);

}

void loop() {
  // put your main code here, to run repeatedly:
  int x;
  for (x = 0; x < 11; x++) {
    Serial << x << ":" << pgm_read_byte(test + x) << "\t";
  }
  Serial << "\n";
  delay(2000);
}