Search code examples
c++lambdaarduinoarduino-esp8266

Operating on objects captured in multiple lambdas


I am making a simple homebrew IoT solution using the esp8266, using the build in libraries for web server routes. These lib functions don't like using functions with arguments so my solution was to use lambdas and capture the variables I need. The problem is when trying to operate on the same instance of an object from two different lambdas, when using the pinPower setter methods that update an int storing the pin power (1 or 0, yes I know a bool would be better) a change in one lambda does not appear in the other.

I think this has to do with lambdas capturing variables by value and it creating a new instance of my class; I have tried capturing outputPinArray[i] as a reference but this just meant that the getter function failed to get the correct value and so failed to do so much as toggle the value (class uses the getter internally). Using a static variable and getter function worked but I want to be able to use multiple instances of the class and so don't want a shared variable like this. I have seen various posts around that seem to point to capturing using the extern keyword but I haven't found much documentation for using this in lambdas and wasn't able to figure out how to use it properly.

This is the code I am working with:

for(int i = 0; i < 1; i++) {
    server.on(path, HTTP_POST, [outputPinArray , argToCheck, i]() mutable {
        // Sets pinNumber variable and turns on or off the arduino pin using outputPinArray[i].setPinPower or .togglePinPower    
    });


    server.on(path, HTTP_GET, [outputPinArray,i](){
        // Send integer value using outputPinArray[i].getPinPower()
    });
}

outputPin class code:

int OutputPin::getPinPower(){
    return pinPower;
}

void OutputPin::setPinPower(int value){
    if(value == HIGH || value == LOW){
        pinPower = value;
        digitalWrite(getPinNum(), pinPower);
}

Any help is appreciated, Thank you!


Solution

  • If I understand your problem correctly, all you need to do is

    server.on(path, HTTP_POST, [&outputPinArray , argToCheck, i]()  {