I'm totally confused. If I read a manual indexed value from an array it is fine, but when it comes from code, it does output 0:
void setup() {
Serial.begin(115200);
while(!Serial){}
}
void loop() {
if (Serial.available()){
byte nibble=Serial.read();
int keyPressed=255;
if (nibble>96 && nibble<123) keyPressed=nibble-97;
if (nibble>64 && nibble<76) keyPressed=nibble-65;
if (keyPressed!=255){
uint8_t keyCode=codes[keyPressed]; // this fills with 0 if you enter c in Serial
// uint8_t keyCode=codes[2] would contain 130,
Serial.println(keyCode,HEX);
}
}
}
const PROGMEM byte codes[]={
B00000010,
B10000010,
B01000010,
... //long list here
Why does a manual selection contain 130 from the array, where it does not work if selected by the variable keyPressed, which contains 2 as well.
Because you're accessing the PROGMEM array incorrectly. When you hard code an index, the compiler realizes your mistake and pulls the correct value for you. When the index is chosen programmatically, the compiler can't fix your error. Start HERE to learn how to correctly access PROGMEM.
I read your link, and tried pgm_read_byte_near
and that fixed it, yet I am sure I've done dozens of Progmem reads without, for example with sprite bitmap arrays. Thanks
I'd be interested in an example of code that correctly accesses PROGMEM on an AVR board using the technique of your first post. That is ... when the index is not known at compile time. Please post that code.
It's probably more likely that the compiler doesn't understand that PROGMEM puts the array in a different address space (that's the linker's job) and just uses the fixed value from the array where it's used as an optimization because it already knows the value at compile time.