20170621

Bounce buttons in Array

This post is derivative of the one I did in this reddit thread. There though the focus was more on how the OP could restructure his code to not only make it work, but also get rid of multiple repetitions of basically the same code.

Anyhow, making the little example to get him on the right track, I stumbled upon another little challenge. Anyone who's been doing any Arduino projects for a while most likely have gotten to use the <Bounce2.h> library.

For those who have not, the short of it is that it relieves you of the task of debouncing buttons manually in code - or for that matter in electronics by routing the input through a schmitt-trigger chip.

Just attach buttons in software to the Bounce object, and you're good to go. Which is fine when you got one to three buttons all assigned their own unique ID. Any more, and it soon looks both tedious and newbish to declare a ton of buttons like so:

Bounce buttonA = Bounce();
Bounce buttonB = Bounce();
Bounce buttonC = Bounce();


Which also bring on the issue of each little 'is a button pressed?' routine need be in triplicate - one for each unique button. Surely stuffing all that stuff into an array is much better?!

Which I set out to do in my little example of 'clean & structured' code. A little research and trial and error later, this is what I came up with:

#include <Bounce2.h>

const byte ledPin[2] = {10, 11};
const byte butPin[2] = {2, 3};

Bounce button[2] = {
  Bounce(butPin[0], 2),
  Bounce(butPin[1], 2)
};

bool ledState[2] = {false, false};

void setup(){
  for(byte i = 0; i < 2; i++){
    pinMode(ledPin[i], OUTPUT);
    pinMode(butPin[i], INPUT_PULLUP);
    button[i].attach(butPin[i]);
  }
}

void loop(){
  for(byte i = 0; i < 2; i++){
    if(getButton(i)){
      flipLED(i);
    }
  }
}

bool getButton(byte b){ 
  if(button[b].update() && button[b].read() == LOW){   
    return true;
  } else {
    return false;
  }
}

void flipLED(byte b){
  ledState[b] = !ledState[b];
  digitalWrite(ledPin[b], ledState[b]);
}


The only surprise, and what had me scratching my head a bit, is that each declaration of a Bounce object, need have the max number of objects at the end - after the pin assignment of it.

Another little thing to note that beginners may not realize, is that 0 = false = LOW, and conversely 1 = true = HIGH. So rather than turn the LED on and off through your typical if(this){do that} routine one can save oneself a bit of work and CPU cycles by making the led state variable a bool - essentially a bit - that you can flip easily with the not '!' operator.

Doing proper bitwise operations would be more efficient - but this example was to help a beginner. No need to confuse more than strictly speaking necessary :)