You might want to give a slightly more real-life example so it's a little clearer what you need to achieve but an array of function pointers comes to mind (maybe in combination with a struct).
The below uses a struct with two elements; the first one is the buttonvalue (number) and the second one is a pointer to a function that needs to be executed. Written to give you an idea what can be done
First you can define the struct
struct BUTTONACTION
{
byte number;
void (*action)(byte switchstate);
};
The action is a pointer to a function that takes the 'switchstate' as a parameter
Next you need to write the functions.
void button12(byte switchstate)
{
if(switchstate == HIGH)
{
lcd.print("1");
}
}
void button10(byte switchstate)
{
if(switchstate == LOW)
{
lcd.print("2");
}
}
Now you can populate an array of structs with buttons and associated functions
BUTTONACTION buttonactions[] =
{
{12, button12},
{10, button10},
{11, NULL},
};
For button value 11, there is no function specified so nothing will be executed; just to show how it can be used.
setup() will be your standard setup
and loop() can look like below
byte buttonval = readKeypad();
byte switchstate = digitalRead(A0);
// loop through the possible buttons
for(int cnt=0;cnt<sizeof(buttonactions)/sizeof(buttonactions[0]);cnt++)
{
// if the entered button number matches the nunber in the action table
if(buttonval == buttonactions[cnt].number)
{
// and if there is a function specified
if(buttonactions[cnt].action != NULL)
{
// execute the function
buttonactions[cnt].action(switchstate);
}
// optionally break from for-loop after match
break;
}
}
// reset the enter button number
buttonval = 0;
}
You can finetune to your needs ![]()
Total
// variable declarations and defines
...
...
struct BUTTONACTION
{
...
...
};
// button actions
void button12(byte switchval)
{
...
...
}
...
...
void setup()
{
...
...
}
void loop()
{
...
...
}