如何使用PROGMEM检索存储在表中的int数组?

时间:2016-12-21 08:14:25

标签: arduino

我是Arduino的新手,目前正在学习使用PROGMEM存储变量,这样我就可以节省动态内存。我有13个变量,包括下面我用PROGMEM存储的三个变量。 以下是我在我的函数中存储和使用它的一些变量示例: -

const unsigned int raw_0[62] PROGMEM  = {2600,850,400,500,400,500,450,850,450,850,1350,850,450,450,400,500,400,450,450,400,450,450,450,450,400,450,900,850,900,850,900,450,450,850,900,850,900,850,450,450,900,450,400,450,400,900,450,450,450,400,450,450,450,450,400,450,450,450,450,400,450,};
const unsigned int raw_1[60] PROGMEM = {2600,850,450,450,450,450,450,850,450,850,1350,850,500,400,450,400,450,450,450,450,400,450,450,450,400,450,900,850,900,900,850,450,450,850,850,900,900,900,400,450,900,450,450,400,450,850,450,450,450,450,400,450,450,450,450,400,450,450,850,};
const unsigned int raw_a[100] PROGMEM = {3500,1700,400,450,450,1250,450,400,450,400,450,400,500,400,450,400,450,400,450,400,450,450,400,400,500,400,450,400,450,1300,400,450,450,400,450,400,450,400,450,400,450,400,500,350,500,400,450,400,450,1300,400,400,500,400,450,400,450,400,450,450,400,450,450,400,450,400,450,400,450,400,450,450,400,450,450,400,450,1250,450,400,450,400,500,400,450,400,450,400,450,400,450,400,450,1300,450,400,450,1250,450,};

这是存储变量的表。我从Arduino网站上学习这种方法; https://www.arduino.cc/en/Reference/PROGMEM

const unsigned int* const myTable[13] PROGMEM = {
  raw_0, 
  raw_1, 
  raw_2, 
  raw_3, 
  raw_4,
  raw_5,
  raw_6,
  raw_7,
  raw_8,
  raw_9,
  raw_a,
  raw_b,
  raw_c};

我的问题是,如何使用PROGMEM检索这些变量,例如raw_1和raw_a? 这就是我所做的,但它不起作用: -

unsigned int * ptr = (unsigned int *) pgm_read_word (&myTable [1]);
irsend.sendRaw(ptr,62,38);

我发现的大多数示例都使用String或char数据类型但在我的情况下,我使用数组整数。

1 个答案:

答案 0 :(得分:1)

ptr也是指向PROGMEM的指针,因此您必须通过pgm_read_word读取值(或本例中的值)。 IR library根本不支持(我希望它是正确的)。

无论如何sendRaw实现是这样的:

void  IRsend::sendRaw (const unsigned int buf[],  unsigned int len,  unsigned int hz)
{
    // Set IR carrier frequency
    enableIROut(hz);

    for (unsigned int i = 0;  i < len;  i++) {
        if (i & 1)  space(buf[i]) ;
        else        mark (buf[i]) ;
    }

    space(0);  // Always end with the LED off
}

并且所有使用的方法都是公共的,因此您可以实现自己的功能来执行相同的操作:

void  mySendRaw (IRsend & dev, const unsigned int buf[],  unsigned int len,  unsigned int khz)
{
    // Set IR carrier frequency
    dev.devenableIROut(khz);

    for (unsigned int i = 0;  i < len;  i++) {
        if (i & 1)  dev.space(pgm_read_word(buf+i));
        else        dev.mark (pgm_read_word(buf+i));
    }

    dev.space(0);  // Always end with the LED off
}

// And usage:
mySendRaw(irsend, (const uint16_t*)pgm_read_word(myTable+1), 62, 38);

然而,数组的大小也应该存储在某个地方,所以你可以使用类似的东西:

byte cmd = 1;
mySendRaw(irsend, (const uint16_t*)pgm_read_word(myTable+cmd), pgm_read_word(myTableLenghts+cmd), 38);