首页 > 解决方案 > 如何在 Arduino C++ (FastLED) 的另一个类中使用一个类?

问题描述

我正在为我的房间做一个 ledstip 项目。我正在使用arduino来做到这一点。对于这个项目,我想使用 C++,所以我可以使用 OOP。在我的 ledstrips 工作后,我想创建一个 cluster 类,它使用 strip 类来控制 LED 灯条的特定部分。我不能让它工作。编译器没有给出错误,使用该函数后我看不到任何变化Desk.rgb(0,100,0);

这是我的 .h 文件

#include <FastLED.h>
template<class T>
class Cluster {
  public:
    T Strip;
    int first;
    int last;

    Cluster(T Strip, int first, int last) {
      this->Strip = Strip;
      this->first = first;
      this->last = last;
    }
    
    void rgb(int r, int g, int b){
      Strip.rgb( r,  g,  b, first, last);
    }
};

template<byte pin, int AmountOfLeds>
class Strip {
  public:
    CRGB leds[AmountOfLeds];

    void setup() {
      FastLED.addLeds<WS2812, pin, GRB>(leds, AmountOfLeds);
      rgb(0, 0, 0);
    }
    //hole strip
    void rgb(int r, int g, int b) {
      for (int i = 0; i <= AmountOfLeds - 1; i++) {
        this->leds[i] = CRGB(r, g, b);
      }
      FastLED.show();
    }
    //single led
    void rgb(int i, int r, int g, int b) {
      this->leds[i] = CRGB(r, g, b);
      FastLED.show();
    }
    //range
    void rgb(int r, int g, int b, int f, int l) {
      for (int i = f; i <= l; i++) {
        this->leds[i] = CRGB(r, g, b);
      }
      FastLED.show();
    }

    void hsv(int h, int s, int v) {
      for (int i = 0; i <= AmountOfLeds; i++) {
        this->leds[i] = CHSV(h, s, v);
      }
      FastLED.show();
    }
    void hsv(int i, int h, int s, int v) {
      this->leds[i] = CHSV(h, s, v);
      FastLED.show();
    }
    void hsv(int h, int s, int v, int f, int l) {
      for (int i = f; i <= l; i++) {
        this->leds[i] = CHSV(h, s, v);
      }
      FastLED.show();
    }

    void hsvWhiteBalance(int S, int V) {         //S is yellowness, V is brightness
      hsv(15, S, V);
    }

    void rainbow(float V) {
      for (int i = 0; i <= AmountOfLeds; i++) {
        leds[i] = CHSV( float(i) * (255 / float(AmountOfLeds)), 255, V);
      }
      FastLED.show();
    }
    void rainbow(float p, float V) {
      for (int i = 0; i <= AmountOfLeds; i++) {
        leds[i] = CHSV( float(i) * (255.0 / float(AmountOfLeds) * p), 255, V);
      }
      FastLED.show();
    }
};

这是我的 .ino 文件:

#include "LedClasses.h"
Strip<5, 190> DTVC;

Cluster<Strip<5, 190>> Desk(DTVC, 1, 42);

void setup() {
  Serial.begin(9600);   

  DTVC.setup();

  DTVC.hsvWhiteBalance(153, 50);
  Desk.rgb(0,100,0);
  //DTVC.rgb(Desk, 0, 100, 0);
}

提前致谢。

标签: c++classarduinoarduino-c++

解决方案


不起作用,因为在Cluster构造函数中,您Strip通过复制获取类。然后,在您的示例中,您有 2 个实例Stripe:一个在全局上下文中,一个在Cluster. 您在全局上下文中调用Stripe::setup(调用)实例(在 FastLED 库中注册公共字段的地址),但稍后您调用存在于您内部且具有不同字段的实例。FastLED.addLedsStripe::ledsrgbClusterStripe::leds

为了快速修复它(虽然不是很干净),您可以重新设计构造函数以接受引用而不是复制:

class Cluster {
  public:
    T& strip;
    int first;
    int last;

    Cluster(T& s, int f, int l): strip(s), first(f), last(l) {}

或者,您可以重新设计您的架构,不要过多地使用模板(您可以使用constexpr参数来代替)。


推荐阅读