/*
Wokwi | questions
Debounce not working for buttons
Answered
October 7, 2025
Very Spooky Jayden
OP
 — Yesterday at 10:51 PM
Why is the debounce not working? I'm a bit rusty with Arduino code so here I am...
https://wokwi.com/projects/444211180071353345
*/
// define button pins
#define C_BUTTON 12
#define D_BUTTON 11
#define E_BUTTON 10
#define F_BUTTON 9
#define G_BUTTON 8
#define A_BUTTON 7
#define B_BUTTON 6
#define SELECTION_BUTTON 5
// define potentiometer pin
#define SELECTION_POT A7
// used for debounce
#define NUM_BUTTONS 8
// I2C pins for the screen
#define SCL A5
#define SDA A4
int button_array[] = {C_BUTTON, D_BUTTON, E_BUTTON, F_BUTTON, G_BUTTON, A_BUTTON, B_BUTTON, SELECTION_BUTTON};
int button_states[NUM_BUTTONS];
int old_button_states[NUM_BUTTONS];
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("START");
  for (int button = 0; button < NUM_BUTTONS; button++) {
    pinMode(button_array[button], INPUT_PULLUP);
    old_button_states[button] = 1;
  }
  pinMode(SELECTION_POT, INPUT);
}
int buttonCheck() {
  for (int btn = 0; btn < NUM_BUTTONS; btn++) {
    button_states[btn] = digitalRead(button_array[btn]);
    if (button_states[btn] != old_button_states[btn]) {
      old_button_states[btn] = button_states[btn];
      //Serial.println("Button change ");
      //Serial.println(button_array[btn]);
      if (button_states[btn] == LOW) {
        Serial.print(button_array[btn]);
        Serial.println(" pressed");
        return button_array[btn];
      } else {
        return -1;
      }
    }
    delay(10);
  }
  return 0;
}
void loop() {
  // put your main code here, to run repeatedly:
  int button = buttonCheck();
  if (button != 0) {
    Serial.println(button);
  }
}