A way to access flash memory avoiding pgm_read (avr microcontrollers)

484 Views Asked by At

When you want to access to flash memory you have to write something like this:

constexpr uint8_t n PROGMEM = 10;

auto x = pgm_read_byte(&n);

I don't like this way to access memory. I want to access every type of memory in the same way (RAM, flash, EEPROM...). I'd like to write something like this one better:

constexpr uint8_t n = 10; // constexpr tells the compiler: 
                          // eh! I'm not planning to write in this variable
                          // so you can put it in flash memory

auto x = n; // copy n into x (but x is uint8_t, not constexpr)

I naively try to implement this like:

 namespace Progmem{
      class uint8_t{
           constexpr uint8_t(::uint8_t x):v{x}{}

           // TODO: operator uint8_t() const {return pgm_read_byte(&v);}
           // private:
           ::uint8_t v PROGMEM;
      };
 }

and to test it this way:

 constexpr Progmem::uint8_t n = 10;

 auto x = pgm_read_byte(&(n.v));

It compiles but the number store in x is not right.

How can I write this class?

Thank you.

1

There are 1 best solutions below

0
On

You could use flash_constant from fmorgner's AVR++ library.

Before (example demo_progmem.c):

#include <avr/pgmspace.h>
#include <stdint.h>

int const demo PROGMEM = 1;

int main()
  {
  return pgm_read_word(&demo);
  }

after (example demo_progmem.cpp):

#include <avr/flash_constant.hpp>
#include <avr/cstdint.hpp>

auto const demo = avr::flash_constant{1};

int main()
  {
  return demo;
  }