Lambda timer

You can modify the code as follows:


void SquareWave(int pin,
                unsigned long offtime,
                unsigned long ontime,
                int Vpinled,
                float flow1,
                float flow2)
{
  // to pass parameters to lambda function. You can use global vars
  static    int   _pin      = pin;
  static    int   _Vpinled  = Vpinled;
  static  float   _flow2    = flow2;

  analogWrite(pin, flow1);
  Blynk.virtualWrite(Vpinled, 0);

  timer.setTimeout(ontime, []()
  {
    analogWrite(_pin, _flow2);
    Blynk.virtualWrite(_Vpinled, 255);
  });
}

Lambda function, if using parameters, not global or static, inside the function, is a little bit complicated, and will create non-captured errors as you experienced. If you need more info, please read

https://en.cppreference.com/w/cpp/language/lambda

captures - a comma-separated list of zero or more captures, optionally beginning with a capture-default.
See below for the detailed description of captures.

A lambda expression can use a variable without capturing it if the variable

  • is a non-local variable or has static or thread local storage duration (in which case the variable cannot be captured), or
  • is a reference that has been initialized with a constant expression.

A lambda expression can read the value of a variable without capturing it if the variable

  • has const non-volatile integral or enumeration type and has been initialized with a constant expression, or
  • is constexpr and has no mutable members.
1 Like