[SOLVED] Unable to pass digitalPin to lambda timer function

I’m trying to create a function that turn on a relay after a certain duration for few seconds. This my code:

void timerToggleRelay(long waitTime, long duration, int relayPin){
  timer.setTimeout(waitTime,[](){
    digitalWrite(relayPin, HIGH);
    timer.setTimeout(duration, [](){
      digitalWrite(relayPin, LOW);
    });
  });
  return;
} 

However, I got this error

Arduino: 1.8.10 (Windows 10), Board: "WeMos D1 R2 & mini, 80 MHz, 4M (1M SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 921600"

C:\Users\...\AppData\Local\Temp\arduino_modified_sketch_34006\sketch_feb25b.ino: In lambda function:

sketch_feb25b:105:18: error: 'relayPin' is not captured

     digitalWrite(relayPin, HIGH);

                  ^

sketch_feb25b:106:22: error: 'duration' is not captured

     timer.setTimeout(duration, [](){

                      ^

Multiple libraries were found for "ESP8266WiFi.h"
 Used: C:\Users\...\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.1\libraries\ESP8266WiFi
Multiple libraries were found for "BlynkSimpleEsp8266.h"
 Used: C:\Users\...\Documents\Arduino\libraries\Blynk
exit status 1
'relayPin' is not captured

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

What is my mistake here?

Hello,

long waitTime = 1000L;
long duration = 2000L;
int relayPin = 12;

void timerToggleRelay(){
  timer.setTimeout(waitTime,[](){
   digitalWrite(relayPin, HIGH);
    timer.setTimeout(duration, [](){
     digitalWrite(relayPin, LOW);
     });
  });
} 

This should work.

1 Like

You also can have a look at detailed explanation at

1 Like

Thanks @Madhukesh, @khoih. It’s my first time learning about lambda function.

1 Like