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);
}
}
Your are copying Bounce objects into and out of the button array. E.g.
However, since Bounce doesn't implement means for copying objects
buttons[i] = b
simply copiesb
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.