PROGMEM strange behaviour

Hello,
this code below should send one stored number each 500ms. However it gives me totally strange numbers. It can be fixed by deleting "PROGMEM" word, or by replacing "random(60)" by some fixed number. I am beginner and was not able to figure out what is wrong. Thank you for any hint.
My setup is Arduino Nano ATMega328P- chinese copy, Arduino IDE 1.8.19, running on Mint

const long primeNo[60] PROGMEM  = {58687, 58693, 58699, 58711, 58727, 58733, 58757, 58763, 58771, 58787,
                                   58789, 58831, 58889, 58897, 58901, 58907, 58909, 58913, 58921, 58937, 
                                   58943, 58963, 58967, 58979, 58991, 58997, 59009, 59011, 46819, 46829,
                                   46831, 46853, 46861, 46867, 46877, 46889, 46901, 46919, 46933, 46957,
                                   46993, 46997, 47017, 47041, 47057, 47059, 47087, 47093, 47111, 47119,
                                   47123, 47129, 47137, 47143, 47147, 47149, 47161, 47189, 47207, 47221};
void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop() {
  Serial.println(primeNo[random(60)]);
  delay(500);
}

Here you can see typical numbers I am receiving:
0
0
9896312
-67584
0
101058054
207
207
162
101058054
101058054
3

A random number between min and max-1. Data type: long .

Cast to int before the array index.

Serial.println(primeNo[int random(0, 59)]);

Welcome to the forum

  Serial.println(primeNo[random(60)]);

That is not how your read data from PROGMEM

Try

  Serial.println(pgm_read_dword(&primeNo[random(60)]));
2 Likes

Perhaps try something like this:

Serial.println(pgm_read_dword(primeNo + random(60)));
1 Like

Not sure why nor why 59

The reason it works with a fixed number is that the compiler can resolve the reference to a specific number in the array, then hard codes that into the print, completely eliminating the array to optimize the memory use.

1 Like

Hi,
yes, it is something, what I tried on the beginning.


  int randNo = random(0, 59);
  Serial.println(primeNo[randNo]);

But the result is the same as before.

The problem is how you are trying to read the values from PROGMEM

Did you try the suggestion in post #3 ?

Yes, I need to read documentation more carefully. Thank you. It works !

Hi, yes it works, thank you all. I need to read documentation more carefully. Altrough the fact it works with fixed number mislead me to wrong conclusion.

Fixed number ?

Yes, this compiler "shortcut" with fixed number mislead me a bit. Now, it is clear. Thank you.

Yes if everything is static the optimizer becomes very smart and gets rid of everything that is not needed !

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.