【问题标题】:A way to access flash memory avoiding pgm_read (avr microcontrollers)一种避免 pgm_read 访问闪存的方法(avr 微控制器)
【发布时间】:2019-01-04 18:23:56
【问题描述】:

当你想访问闪存时,你必须这样写:

constexpr uint8_t n PROGMEM = 10;

auto x = pgm_read_byte(&n);

我不喜欢这种访问内存的方式。我想以相同的方式访问每种类型的内存(RAM、闪存、EEPROM……)。我想写这样一个更好的东西:

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)

我天真地尝试这样实现:

 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;
      };
 }

并以这种方式进行测试:

 constexpr Progmem::uint8_t n = 10;

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

它可以编译,但 x 中存储的数字不正确。

我该如何写这门课?

谢谢。

【问题讨论】:

    标签: c++ avr progmem


    【解决方案1】:

    你可以使用fmorgner's AVR++ library中的flash_constant

    之前(例如 demo_progmem.c):

    #include <avr/pgmspace.h>
    #include <stdint.h>
    
    int const demo PROGMEM = 1;
    
    int main()
      {
      return pgm_read_word(&demo);
      }
    

    之后(例如 demo_progmem.cpp):

    #include <avr/flash_constant.hpp>
    #include <avr/cstdint.hpp>
    
    auto const demo = avr::flash_constant{1};
    
    int main()
      {
      return demo;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多