the OP may find how this code uses function ptrs and ptrs to arguments to those function insightful. The code manages buttons that perform different "commands". Those cmds are described in a table
int LhTopLimit;
const byte PinLeds [] = { 13, 12, 11 };
const int NLed = sizeof(PinLeds);
// -----------------------------------------------------------------------------
void incVar (
int val,
void *adr )
{
Serial.print (" ");
Serial.println (*(int *)adr += val); // cast void* to int*
}
// ---------------------------------------------------------
void setVar (
int val,
void *adr )
{
Serial.print (" ");
Serial.println (*(int *)adr = val); // cast void* to int*
}
// ---------------------------------------------------------
void toggle (
int pin,
void *_unused_ )
{
digitalWrite (pin, ! digitalRead (pin));
}
// ---------------------------------------------------------
struct ButCmd {
const byte Pin;
void (*func) (int, void*); // pointer to function
int arg1;
void *arg2; // undefined type
const char *desc;
byte butState;
unsigned long msec;
}
cmds [] = {
{ A1, toggle, 13, (void*) 0, "LED-13" },
{ A2, setVar, 1, (void*) & LhTopLimit, "LhTopLimit" },
{ A3, incVar, -1, (void*) & LhTopLimit, "LhTopLimit--" },
};
const int Ncmd = sizeof (cmds)/sizeof(ButCmd);
// -----------------------------------------------------------------------------
void setup ()
{
Serial.begin (9600);
for (int i = 0; i < NLed; i++)
pinMode (PinLeds [i], OUTPUT);
for (int i = 0; i < Ncmd; i++) {
pinMode (cmds [i].Pin, INPUT_PULLUP);
cmds [i].butState = digitalRead (cmds [i].Pin);
}
}
// -----------------------------------------------------------------------------
const unsigned long MsecTmout = 500;
void loop ()
{
unsigned long msec = millis ();
for (int i = 0; i < Ncmd; i++) {
if (msec - cmds [i].msec < MsecTmout)
continue;
byte but = digitalRead (cmds [i].Pin);
if (cmds [i].butState != but)
cmds [i].butState = but;
if (LOW == but) {
cmds [i].msec = msec;
Serial.println (cmds [i].desc);
(*cmds [i].func) (cmds [i].arg1,cmds [i].arg2);
}
cmds [i].msec = msec;
}
}