1

Why would this simple code which prints out array values give the right value 240 when the array is addressed with index directly addressed by number but give 184 when addressed usin a varibale n that is incrementing?

PROGMEM const unsigned char COLSA[8] = { 
 240, 240, 240, 240, 
 240, 240, 240, 240}; //Stored pattern
void setup() {
 Serial.begin(9600);
}
void loop() {
 int n;
 for(n=0;n<8;n=n+1) 
 {
 Serial.println(n);
 Serial.println(COLSA[1]);
 //n=2; //If I use n in this way things are fine. It prints 240. Else it prints 184
 Serial.println(COLSA[n]);
 }
 delay(100);
}
Majenko
106k5 gold badges81 silver badges139 bronze badges
asked Nov 21, 2015 at 10:25

1 Answer 1

4

Because the array is a constant the compiler can, when it knows the entry number (i.e., using a numeric literal) replace the access to the array with the contents of that array index - so it's not looking up the value of 240 at runtime, instead the value 240 has been used where the access to the array was.

However, when accessing it using a variable the compiler can't do that, so it has to actually access the array in RAM.

BUT the array isn't in RAM, it's in PROGMEM, so the address that it's being given for where the array is located is completely wrong. You're program is telling it "It's in the bedroom" - but you're omitting the important information of: "... of the house next-door.".

PROGMEM and RAM are two completely different things accessed through two completely separate data and address buses - just like two separate houses, they both have a number of rooms in them, and those rooms are called the same thing, but they're not the same room.

So instead of accessing an array by index like that you have to use special instructions to say "Get this value from PROGMEM", such as:

 Serial.println(pgm_read_byte_near(COLSA + v));

That says "Give me the byte that is located at v addresses on from the start of the COLSA array in PROGMEM.

answered Nov 21, 2015 at 10:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.