Arduino Teensy 数组的 Bounce 实际上没有更新

Arduino Teensy array of Bounce not actually updating

我对 Arduino 和 C 本身很陌生,但我不明白为什么数组不起作用,而完整性检查却起作用。

在我看来,两者都应该运行良好。我猜我遗漏了一些关于 C 中的数组如何工作的关键信息。

代码完整性:

#include <Bounce2.h>

#define BUTTON_AMOUNT 1
#define DEBOUNCE_INTERVAL 25

const int ledPin = LED_BUILTIN;

//Bounce *buttons[BUTTON_AMOUNT];
Bounce buttons[BUTTON_AMOUNT];
Bounce b1 = Bounce();

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

  pinMode(ledPin, OUTPUT);

  for (int i = 0; i < BUTTON_AMOUNT; i++) {
    Bounce b = Bounce();
    b.attach(i, INPUT_PULLUP);
    b.interval(DEBOUNCE_INTERVAL);

    buttons[i] = b;

    // buttons[i] = new Bounce();
    // (*buttons[i]).attach(i, INPUT_PULLUP);
    // (*buttons[i]).interval(DEBOUNCE_INTERVAL);
  }

  b1.attach(0, INPUT_PULLUP);
  b1.interval(25);
}

void loop () {
  for (int i = 0; i < BUTTON_AMOUNT; i++) {
    // Serial.println("looping ...");

    Bounce b = buttons[i];
    b.update();

    if (b.rose()) {
      // Serial.println("rising edge");
      digitalWrite(ledPin, LOW);
    }
    if (b.fell()) {
      // Serial.println("falling edge");
      digitalWrite(ledPin, HIGH);
    }
  }

  // sanity check
  b1.update();

  if (b1.rose()) {
    Serial.println("B1 - rising edge");
    digitalWrite(ledPin, LOW);
  }
  if (b1.fell()) {
    Serial.println("B1 - falling edge");
    digitalWrite(ledPin, HIGH);
  }
}

您正在将 Bounce 对象复制到按钮数组中或从中复制出来。例如

...
  for (int i = 0; i < BUTTON_AMOUNT; i++) {
    Bounce b = Bounce();
    b.attach(i, INPUT_PULLUP);
    b.interval(DEBOUNCE_INTERVAL);

    buttons[i] = b;  // <- bitwise copy
...

但是,由于 Bounce 没有实现复制对象的方法 buttons[i] = b 只是将 b 按位复制到数组中,这是行不通的。

无需将元素从/复制到数组中,您只需访问它们即可。这里的工作代码展示了如何做到这一点。

#include "Bounce2.h"

constexpr int BUTTON_AMOUNT = 5;
constexpr int DEBOUNCE_INTERVAL = 25;
constexpr int ledPin = LED_BUILTIN;

Bounce buttons[BUTTON_AMOUNT];  // this already constructs the buttons in the array, you can use them directly

void setup() {
  pinMode(ledPin, OUTPUT);

  for (int i = 0; i < BUTTON_AMOUNT; i++) {
    buttons[i].attach(i, INPUT_PULLUP);      // directly access the Bounce objects in the array
    buttons[i].interval(DEBOUNCE_INTERVAL);
  }
}

void loop () {
  for (int i = 0; i < BUTTON_AMOUNT; i++) {
    buttons[i].update();

    if (buttons[i].rose()) {
      Serial.printf("rising edge B%u\n", i);
      digitalWrite(ledPin, LOW);
    }
    if (buttons[i].fell()) {
      Serial.printf("falling edge B%u\n", i);
      digitalWrite(ledPin, HIGH);
    }
  }
}