Const int and const PROGMEM int

I have a question. I adopted the use of const int over #define. Thinking I was doing good.

Today I learned that my const int consumes RAM, atleast the arrays do. In fact 75% of my RAM consists out of const ints. I already wondered why my program would use so much RAM.

Now my RAM memory is full. I googled the above and I used PROGMEM in the declarations. Thinking it would solve my memory problem. And it does... I got my 75% back.

What I don't know, is why all my arrays are now broken or how I can fix this.

For instance I have

const byte accessoryAddresses[] = // conversion array for accessory panel items to Xnet addresses
{
    1,  9, 
    2, 10, 
    3, 11, 
    4, 12, 
    5, 13, 
    6, 14, 
    7, 15, 
    8, 16, 
} ;

And when I try to do:

Serial.println((int)accessoryAddresses[Address]); 

(with address being 0-15)

I get complete random values. My best guess would be that PROGMEM stores the constants on places which are also used by heap or stack during runtime or something...???

What is happening?
Can I fix this?
And if so: how?

Also, why does const int uses memory in the first place? I thought it was just a compile time thingy to replace the functionality of #define to eliminate certain macro pitfals ???

Regards,

Bas

const byte accessoryAddresses[] = // conversion array for accessory panel items to Xnet addresses

Is this array actually being stored in PROGMEM ?

If the array is actually stored in PROGMEM, then you need to tell the compiler to access it from PROGMEM. in the case of a byte, use pgm_read_byte().

  Serial.println((int)pgm_read_byte(&accessoryAddresses[Address]));

Here is a reference page on the different methods of accessing program memory https://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html

Because on an AVR processor the program memory (FLASH/PROGMEM) is not in the same address space as RAM. All initialized data is copied from PROGMEM to RAM before the sketch starts.

Initialized variables marked 'PROGMEM' are not copied to RAM and can only be accessed by special functions that use the instruction for copying data from FLASH.

Yes it is but i forgot to insert it in my post.

Isn't there an other way to use an array of constants by which all elements are replaced by their values at compile-time or must one really use the progmem functions?

Regards,

Bas

If the compiler can determine the specific element of the array being used at compile time, then it will hard-code that value into the code and not store the array. Any reference to the array that cannot be determined at compile-time requires that the array be stored in memory.

Ah I get it. If I use the array elements using a variable for index.. RAM is needed.

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