lamp,
@lamp@kitty.haus avatar
const int buttonPins[] = {2,3,4,5,6,7};
int lastBtnState[6] = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
unsigned long lastBtnTime[6];

void setup() {
  for (int i = 0; i < 6; i++) {
    pinMode(buttonPins[i], INPUT_PULLUP);
  }
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  for (int i = 0; i < 6; i++) {
    int btnState = digitalRead(buttonPins[i]);
    if (btnState != lastBtnState[i]) {
      if (micros() - lastBtnTime[i] > 1000) {
        OnBtnStateChange(i, !btnState);
      }
      lastBtnState[i] = btnState;
      lastBtnTime[i] = micros();
    }
  }
}

void OnBtnStateChange(int btn, bool pressed) {
  Serial.print(btn);
  Serial.println(pressed);
  digitalWrite(LED_BUILTIN, pressed);
}
gentoobro,
@gentoobro@gleasonator.com avatar

@lamp Depending on your hardware you can run out of ram relatively quickly with button debouncing. I use the Nano 168's a lot and they're rather cramped.

A good solution is to use X-Lists (a C macro trick, look it up) for the configuration of the desired button names. Using it, create an enum for the button ordinals, then another that's defined as 1 << by the ordinal of the same button. Now you have bit masks and can write a loop to check button states and debounce them (Have an extra enum member like "BUTTON_MAX_VALUE" to limit your loop).

You also don't need longs for the button times. You only need accumulators that go up to the debounce time. Set the accumulator to zero then increment it by the delta since the last loop. You can easily make them 16 bit unsigned ints, or even 8 bit unsigned chars if you put a divider on the delta-t.

lamp,
@lamp@kitty.haus avatar

@gentoobro it uses up ram? doesnt it just rewrite the same variables?

icedquinn,
@icedquinn@blob.cat avatar

@lamp @gentoobro defining the counters uses up some of your RAM. 4-byte integers add up when you only have like 4k of memory for the whole firmware.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • random
  • Hentai
  • doujinshi
  • announcements
  • general
  • All magazines