Getter for button state, best practice ?

While using the same buttons between multiple states, is there a way to reduce the code by using getters for the button state? The following code is an example representing the question. This is not an issue with two states, but if I end up on 7-8, it seems this way is not efficient.

switch (state)
{
 case 0:
   if (digitalRead(BTN_1) == LOW) 
       Serial.print("Case 0, button 1");
   if (digitalRead(BTN_2) == LOW) 
       Serial.print("Case 0, button 2");
   break;
 case 1:
   if (digitalRead(BTN_1) == LOW) 
       Serial.print("Case 1, button 1");
   if (digitalRead(BTN_2) == LOW) 
       Serial.print("Case 1, button 2");
   break;
}

Thank you :slight_smile:

Read the button states before the switch/case (possibly in a function to keep things neat) and store them in variables that are tested in the states. You have not shown where the value of state is derived which may affect the answer

Code tags look like this [​code][​/code]

Hoist the read outside the if...

bool but1pressed = !digitalRead(BUT_1);
bool but2pressed = !digitalRead(BUT_2);
switch (state) {
  case 0:
    ....
  case 1:
    ....
}

This is assuming a non-trivial example where the case statements do something other than printing the button states. If that’s all they are doing, what’s the point of the switch case at all?

glenter:
While using the same buttons between multiple states, is there a way to reduce the code by using getters for the button state?

What is a 'getter' and how would you use it in your example?