Debounce function for multiple buttons not working correctly

Pretty sure this is a basic problem with some multiple button debounce code I’ve written.

When the button is held, load=true is triggered over and over.
When buttons = 6 (ie, not pin 5 as I should be), load = true is also triggered.
Code paraphrased for simplicity, as I’m sure this is a simple problem!
**bool load = false;

byte buttons = {5, 6};

int buttonState = {0};

int lastButtonState = {LOW};

long lastDebounceTime = {0}; 
long debounceDelay = 50;

void loop() {

  if (load == true) {
    load = false;


void checkInput() {

for (int b = 0; b < sizeof(buttons); b++) {
    int input = digitalRead(buttons[b]);
    if (input != lastButtonState[b]) {
      lastDebounceTime[b] = millis();

if ((millis() - lastDebounceTime[b]) > debounceDelay) {

if (input != buttonState[b]) {
        buttonState[b] = input;

if (buttonState[b] == HIGH) {
          if (buttons[b] == 5) {
            load = true;
    lastButtonState[b] = input;

It seems that buttonState[] and lastButtonState[] are defined with a single value, so only element zero is valid. Yet, the code seems to be trying to read two buttons. What happens if you define these with two elements instead of one?

Hmm, I thought if you initialised an array with just {0} then it would make everything in that array 0.

That's got it. Nice one. Thanks.

On that topic though, what is an array initialised with as default? NULL?

Actually, what the array contains depends on its data type and its scope. If the item is defined with global scope, integer data types are initialized with zero, reference types with null. However, I never assume the compiler initializes a data item. I always do that myself, if for no other reason than to document my intentions.

I thought if you initialised an array with just {0} then it would make everything in that array 0.

Yes, but if you want a multi element array then you need either an explicit number of elements declared or given values.

Right. The problem was't the initialization, it was the number of elements.

int buttonState[] = {0};

Makes a 1 element array with a 0 in the only element. Since you didn't say how many elements, it figured it out from the initializer list. Only one initializer, so only one element.

int buttonState[2] = {0};

Would make a 2 element array with 0's all the way through.


int buttonState[] = {0 , 0};

Now it sees two in the list so it makes a 2 element array.

Wouldn't it be easier wait until the debounce period expires and then read the state of all the buttons into an array.