如何将touchAttachInterrupt与类的成员函数一起用作回调函数


Class A {
public:
A();
void onTouch();
}
A::A() {
touchAttachInterrupt(1, std::bind(&A::onTouch, this), 40)
}

这对我的ESP32不起作用。touchAttachInterrupt的定义是:

void touchAttachInterrupt(uint8_t pin, void (*userFunc)(void), uint16_t threshold);

我的代码导致编译错误,

error: cannot convert 'std::_Bind_helper<false, void (TouchPin::*)(), TouchPin*&>::type' {aka 'std::_Bind<void (TouchPin::*(TouchPin*))()>'} to 'void (*)()

看起来touchAttachInterrupt()只接受一个简单的函数指针,不接受其他指针。不能将其传递给函数对象。如果您希望保留回调方法和拥有它的对象之间的链接,则必须手动执行。无论如何,ESP IDF中都是C语言——任何方便的C++功能都将无法工作,除非它留在C++领域。

ESP IDF中一些更好的C回调API允许您将单个用户参数与函数指针一起传递,当回调被调用时,函数指针会被传递回您。该参数可用于解析对象指针。遗憾的是,本API中的情况并非如此。Arduino确实倾向于以这些有用的小钩子为代价来简化其接口。

所以你几乎被";"老好人";singleton模式。

Class A {
public:
A();
void onTouch();
static void touchCallback() {
if (myself) {
myself->onTouch();
}
}
protected:
A* myself {nullptr};
}
A::A() {
assert(A::myself == nullptr);
A::myself = self;
touchAttachInterrupt(1, A::touchCallback, 40);
}

最新更新