首页 > 解决方案 > 错误:在 Arduino 类的常量表达式中使用“this”

问题描述

我正在尝试为 arduino 项目编写一个类,我使用http://paulmurraycbr.github.io/ArduinoTheOOWay.html中的信息作为指南。

我想设置一个灯条以供进一步使用并不断收到错误消息:错误:在常量表达式中使用“this”。

我的代码如下所示:

#include <FastLED.h>

#define LED_STRIP_PIN 2
#define LED_STRIP_NUM_LEDS 10

//const unsigned char LED_STRIP_PIN = 2;
//const int LED_STRIP_NUM_LEDS = 10;

CRGB leds[LED_STRIP_NUM_LEDS];

class LedStrip {
  unsigned char  pin;

  public:
    LedStrip(unsigned char attachTo) :
      pin(attachTo)
    {
    };

    void setup() {
      FastLED.addLeds<NEOPIXEL, pin>(leds, 10);
    };

};

//LedStrip ledstrip(LED_STRIP_PIN, LED_STRIP_NUM_LEDS);
LedStrip ledstrip(LED_STRIP_PIN);

void setup() {

}

void loop() {

}

我已尝试阅读可能导致此错误的原因,但坦率地说,我不明白其中任何一个。据我了解,似乎我不能在那里使用 const (我认为我不是),因为它可能会在代码执行期间被修改。

完整的错误看起来像thissketch_feb03b.ino:在成员函数'void LedStrip::setup()'中:

sketch_feb03b:20:33: error: use of 'this' in a constant expression

       FastLED.addLeds<NEOPIXEL, pin>(leds, 10);

                                 ^~~

标签: c++arduinofastled

解决方案


您的问题是这pin不是编译时常量,所有模板参数都必须是编译时常量。

可能还有其他选项,但(可能)最简单的选项是pin作为模板参数本身传递:

template<int pin> // make sure type of pin is correct, I don't know what addLeds expect
class LedStrip {
  public:
    LedStrip() //not really needed now
    {
    };

    void setup() {
      FastLED.addLeds<NEOPIXEL, pin>(leds, 10);
    };
};

用法:

//if LED_STRIP_PIN is a compile-time constant, i.e. a macro or a const(expr) value
LedStrip<LED_STRIP_PIN> ledstrip;

//if LED_STRIP_PIN  is obtained at runtime, you cannot it use it at all.
LedStrip<7> ledstrip;

推荐阅读