Dynamic lambdas pass to attachInterrupt
Posted: Sat Nov 30, 2024 2:40 am
Hello,
I would like to have a common function that receives any PIN number as argument, then create a common ISR using attachInterrupt on that pin.
I decided to use lambda for dynamic purpose. However, I got stucked at how to pass the pin number to callback function.
For more details, please see the code below, function LocalRegisterButton, I would like to simplize that function so that I can call attachInterrupt on any pin input.
Currently I cannot do that because attachInterrupt does not accept a captured-by-value lambda. In the code, you can see line 18 where lambda starts. I want to refactor that code to utilize pin variable.
Any tries, you can test your code on my Wokwi project for this code here:
https://wokwi.com/projects/415904203034773505
Thank you.
I would like to have a common function that receives any PIN number as argument, then create a common ISR using attachInterrupt on that pin.
I decided to use lambda for dynamic purpose. However, I got stucked at how to pass the pin number to callback function.
For more details, please see the code below, function LocalRegisterButton, I would like to simplize that function so that I can call attachInterrupt on any pin input.
Currently I cannot do that because attachInterrupt does not accept a captured-by-value lambda. In the code, you can see line 18 where lambda starts. I want to refactor that code to utilize pin variable.
Any tries, you can test your code on my Wokwi project for this code here:
https://wokwi.com/projects/415904203034773505
Thank you.
Code: Select all
static uint8_t _pin_pressed = 0;
void btnRisingIsrHandler(uint8_t btn_pin)
{
_pin_pressed = btn_pin;
/* Do other stuff for specific pin */
}
void LocalRegisterButton(uint8_t pin)
{
/* I would like to simplize this function based on *pin* variable */
pinMode(pin, INPUT_PULLUP);
switch ( pin )
{
case 4:
attachInterrupt(4,
/* Lambda start */
[]() IRAM_ATTR {
/* The problem is that I must hard-code the number 4 here */
/* I want to use *pin* variable to remove "case 5:" below */
btnRisingIsrHandler(4);
}
/* Lambda end */
,
RISING);
break;
case 5:
attachInterrupt(5, []() IRAM_ATTR {
btnRisingIsrHandler(5);
},
RISING);
break;
/* Other cases for all possible PIN numbers */
}
}
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32-S3!");
LocalRegisterButton( 4 );
LocalRegisterButton( 5 );
}
void loop() {
if (_pin_pressed > 0) {
Serial.printf("Pin pressed: %d\n", _pin_pressed);
_pin_pressed = 0;
}
delay(10); // this speeds up the simulation
}