Is there a way to define the handler function of an attachInterrupt() using some indirect method? My code needs to check (outside of loop()) the change in status of 5 physical switches attached to 5 pins of an ESP32 and the code gets repetitive when creating the handler functions as well as when creating the attachInterrupt() ´s.
I mean, it works, but it bugs me to see something that perhaps can be handled inside a for() loop. I went through Function Pointers in Gammon's Forum but my comprehension ability hit a wall.
Thanks!
typedef struct {
const uint8_t PIN;
bool changed;
bool value;
} fSwitch;
fSwitch FS[5] = {{27,0,0},{33,0,0},{15,0,0},{32,0,0},{14,0,0}};
bool sFlag = false;
void IRAM_ATTR chkFS0() {
FS[0].changed = true;
FS[0].value = digitalRead(FS[0].PIN);
sFlag = true;}
void IRAM_ATTR chkFS1() {
FS[1].changed = true;
FS[1].value = digitalRead(FS[1].PIN);
sFlag = true;}
void IRAM_ATTR chkFS2() {
FS[2].changed = true;
FS[2].value = digitalRead(FS[2].PIN);
sFlag = true;}
void IRAM_ATTR chkFS3() {
FS[3].changed = true;
FS[3].value = digitalRead(FS[3].PIN);
sFlag = true;}
void IRAM_ATTR chkFS4() {
FS[4].changed = true;
FS[4].value = digitalRead(FS[4].PIN);
sFlag = true;}
void setup() {
Serial.begin(115200);
for (byte i=0; i<5; i++) {
pinMode(FS[i].PIN,INPUT);
FS[i].value = digitalRead(FS[i].PIN); // initial state of each switch
}
attachInterrupt(FS[0].PIN,chkFS0,CHANGE);
attachInterrupt(FS[1].PIN,chkFS1,CHANGE);
attachInterrupt(FS[2].PIN,chkFS2,CHANGE);
attachInterrupt(FS[3].PIN,chkFS3,CHANGE);
attachInterrupt(FS[4].PIN,chkFS4,CHANGE);
}
void loop() {
if (sFlag) { // if any PIN has changed
sFlag = false;
for (byte i=0; i<5; i++)
if (FS[i].changed) { // determine which PIN changed
Serial.println("FS" + String(i) + "=" + String(FS[i].value));
FS[i].changed = false;
}
}
}