thomasfredericks / Bounce2

Debouncing library for Arduino and Wiring
MIT License
584 stars 172 forks source link

Question regarding multiple button instances in a switch statement. #95

Closed Fusionlight13 closed 3 months ago

Fusionlight13 commented 3 months ago

I made a function with a switch statement to call each button by value to update and return the .pressed method. Multiple presses are returning true which is really confusing me. I use the INPUT_PULLUP mode and attach the wires to ground and the digital pins. I can't figure out if it's an issue with my wiring or the library.

bool buttonClicked(int id)
{
  bool buttonBool;
  switch(id)
  {
    case 1:
      button1.update();
      buttonBool = button1.pressed();
      break;
    case 2:
      button2.update();
      buttonBool = button2.pressed();
      break;
    case 3:
      button3.update();
      buttonBool = button3.pressed();
      break;
  }
  return buttonBool;
}
void loop() {
  // put your main code here, to run repeatedly:
  if(buttonClicked(1))
  {
    changeLed();
  }
    else if(buttonClicked(2))
  {

    Serial.println("Button 2 has been pressed!");
  }
  else if(buttonClicked(3))
  {
    Serial.println("Button 3 clicked!");
  }
}
thomasfredericks commented 3 months ago

It is probably your code. The else ifstatements inloop()do not make sense in this context and should be replace with separate if statements. Otherwise the button updates are not consistently executed every loop.

If you want an else if structure, run all updates first in a separate block and then check if they were pressed in a separate else ifblock.

thomasfredericks commented 3 months ago

For further issues on general coding please use https://forum.arduino.cc/latest

Fusionlight13 commented 3 months ago

Thanks for the help!