Arduino Teensy array of Bounce not actually updating

323 views Asked by At

Im quite new to Arduino and C itself, but I can't figure out why the array does not work, while the sanity check does.

It seems to me that both should operate fine. I'm guessing I'm missing some small bit of crucial info with regards to how arrays in C work.

The entirity of the code:

#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);
  }
}
1

There are 1 answers

0
luni64 On BEST ANSWER

Your are copying Bounce objects into and out of the button array. E.g.

...
  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
...

However, since Bounce doesn't implement means for copying objects buttons[i] = b simply copies b bitwise into the array which won't work.

Instead of copying the elements out of / into the array you can simply access them. Here working code showing how to do that.

#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);
    }
  }
}