The Smell of Molten Projects in the Morning

Ed Nisley's Blog: Shop notes, electronics, firmware, machinery, 3D printing, laser cuttery, and curiosities. Contents: 100% human thinking, 0% AI slop.

Arduino: Remember the Ampersand with PROGMEM Variables!

Got burned by this one again…

The pgm_read_whatever() functions/macros require the address of the variable stored in PROGMEM (the program Flash ROM), not the variable’s value. More on that in the Arduino doc there.

So, for example, this does not work, no matter how easy it might be to type:

#include <avr/pgmspace.h>
#define TZ_INDEX     3     // hardcoded for simplicity
PROGMEM prog_char TimeZone[8] = {0,-3,-4,-5,-6,-7,-9,-10};
char TZOffset;
TZOffset = pgm_read_byte(TimeZone[TZ_INDEX]);

What you really want looks like this:

TZOffset = pgm_read_byte(&TimeZone[TZ_INDEX]);

See the difference?

Maybe next time I’ll remember that…

Comments

6 responses to “Arduino: Remember the Ampersand with PROGMEM Variables!”

  1. Allen Avatar
    Allen

    Thanks – that is exactly what I was missing

    1. Ed Avatar

      Hope it took you less time to find the answer than it did for me…

      Having written it down, I know the next time I make that blunder, I’ll be on the solution quick as lightning!

  2. david Avatar
    david

    The only problem is that I always seem to make *new* blunders…

    (He says, having just today FINALLY found the Mickeysoft bug/misfeature that’s been blocking his project all bloody week.)

    1. Ed Avatar

      make *new* blunders…

      One of the absolute best programmers I ever worked with kept a notebook of (among other things) the errors he made while hammering out code. He said he eventually gave up recording them, having demonstrated to his own satisfaction that he kept making the same errors over and over again. Not, I must add, very many of them… he’d stopped making the really nasty ones years ago.

  3. StarMan703 Avatar
    StarMan703

    Man you have saved the day…….I have been struggling with reading data using PROGMEM and not getting the right outcome. The one thing missing “&” and it WORKS!!! THANK YOU VERY MUCH!!!

    1. Ed Avatar

      Now, if only we both remember it for the next time!