如果循环迭代多次,指针会神秘地改变

问题描述 投票:0回答:1

此代码是为 Arduino MEGA 编写的。

这是最小的可重现示例:

static const unsigned char PROGMEM test_array[] = {
  '3','2','1','0','1','2','3','3','2','1','0','1','2','3','3','2','1','0','1','2','3','3','2','1','0','1','2','3'
};

bool done = false;

void issue_func(const unsigned char* image, unsigned short image_size)
{
    unsigned int idx = 0;

    unsigned char pixel0;
    unsigned char pixel1;
    unsigned char pixel2;
    unsigned char pixel3;

    do {
        Serial.print("idx: ");
        Serial.println(idx);

        pixel0 = image[idx + 0];
        pixel1 = image[idx + 1];
        pixel2 = image[idx + 2];
        pixel3 = image[idx + 3];

        Serial.print("pixel_0: ");
        Serial.print(pixel0);
        Serial.print(", pixel_1: ");
        Serial.print(pixel1);
        Serial.print(", pixel_2: ");
        Serial.print(pixel2);
        Serial.print(", pixel_3: ");
        Serial.println(pixel3);

        idx += 4;

    } while (idx < image_size);
}

void setup() {
    Serial.begin(115200);
    Serial.write("Starting!\n");
    delay(500);
}

void loop() {
    if (!done) {

        issue_func(test_array, 28);
        done = true;

        delay(5000);

        Serial.println(F("complete!"));
    }
}

经过一次迭代(正确读取字符):

Starting!
idx: 0
pixel_0: 51, pixel_1: 50, pixel_2: 49, pixel_3: 48
complete!

超过一个:

Starting!
idx: 0
pixel_0: 184, pixel_1: 184, pixel_2: 184, pixel_3: 184
idx: 4
pixel_0: 184, pixel_1: 184, pixel_2: 184, pixel_3: 184
idx: 8
pixel_0: 184, pixel_1: 184, pixel_2: 184, pixel_3: 184
idx: 12
pixel_0: 184, pixel_1: 184, pixel_2: 184, pixel_3: 184
idx: 16
pixel_0: 184, pixel_1: 184, pixel_2: 1, pixel_3: 3
idx: 20
pixel_0: 0, pixel_1: 0, pixel_2: 37, pixel_3: 0
idx: 24
pixel_0: 0, pixel_1: 0, pixel_2: 0, pixel_3: 0
complete!

我在这里缺少什么?我对微控制器和 C 语言很陌生,所以我希望这只是我所忽视的东西。是否应该归咎于某种编译器优化?

c++ arduino arduino-c++
1个回答
0
投票

答案是我错误地读出了 PROGMEM。我错过了以下文档:

https://www.arduino.cc/reference/en/language/variables/utilities/progmem/

感谢指出这一点的人。

© www.soinside.com 2019 - 2024. All rights reserved.