I'm trying to write a simple program (as a pre-cursor to a more complicated one) that stores an array of bytes to progmem, and then reads and prints the array. I've looked through a million blog/forums posts online and think I'm doing everything fine, but I'm still getting utter gibberish as output.
Here is my code, any help would be much appreciated!
void setup() {
byte hello[10] PROGMEM = {1,2,3,4,5,6,7,8,9,10};
byte buffer[10];
Serial.begin(9600);
memcpy_P(buffer, (char*)pgm_read_byte(&hello), 10);
for(int i=0;i<10;i++){
//buffer[i] = pgm_read_byte(&(hello[i])); //output is wrong even if i use this
Serial.println(buffer[i]);
}
}
void loop() {
}
If I use memcpy
, I get the output:
148
93
0
12
148
93
0
12
148
93
And if I use the buffer = ....
statement in the for loop (instead of memcpy
):
49
5
9
240
108
192
138
173
155
173
You're thinking about two magnitudes too complicated.
memcpy_P
wants a source pointer, a destination pointer and a byte count. And the PROGMEM pointer is simply the array. So, yourmemcpy_P
line should like likethat's it.
memcpy
(without the "P") will not be able to reach program memory and copy stuff from data RAM instead. That is not what you want.