I had the need to pass some callback functions to some of my generic C++ Arduino classes. So I was asking myself if we can use Lambdas in Arduino.
Here is a small test sketch, to verify this.
#include "TestLambda.h"
void setup() {
auto f1 = [](int number) { Serial.println(number); };
LambdaTest t(f1);
t.callLambda(123);
}
void loop() {
}
And here is the related TestLambda.h content:
#include <functional>
class LambdaTest {
public:
LambdaTest(std::function<void (int n)> lambda){
lambda_ptr = &lambda ;
}
void callLambda(int value) {
(*lambda_ptr)(value);
}
protected:
std::function<void (int n)> *lambda_ptr;
};
This example compiled just fine for a ESP32 – but when I tried to compile for a Arduino Nano, I was getting the error TestLambda.h:1:10: error: functional: No such file or directory. As a conclusion we can’t use std::function on Arduino Boards!
The following alternative however was compiling w/o issue:
typedef void (*func)(int n);
class LambdaTest {
public:
LambdaTest(func lambda){
lambda_func = lambda ;
}
void callLambda(int value) {
(*lambda_func)(value);
}
protected:
func lambda_func;
};
0 Comments