我遇到了关于 Arduino 中的 Protothreading 库的问题。我创建了一个Button
类,它代表一个硬件按钮。现在的想法是你可以附加一个ButtonListener
来监听按钮。如果按下按钮,则clicked()
调用该函数。
#include <Arduino.h>
#include <pt.h>
class ButtonListener {
public:
virtual void clicked() = 0;
virtual void longClicked() = 0;
virtual void tapped(int) = 0;
};
class Button {
static const int RECOIL_TIME = 200;
static const int LONG_CLICK_LENGTH = 1000;
private:
int _pin;
ButtonListener *_listener;
struct pt _thread;
unsigned long _timestamp = 0;
int listenerHook(struct pt *pt) {
PT_BEGIN(pt);
this->_timestamp = 0;
while (true) {
PT_WAIT_UNTIL(pt, millis() - _timestamp > 1);
_timestamp = millis();
if (&this->_listener != NULL) {
this->listenForClick();
}
}
PT_END(pt);
}
void listenForClick() {
boolean longClicked = true;
int state = digitalRead(this->_pin);
if (state == HIGH) {
unsigned long timestamp = millis();
while (true) {
longClicked = millis() - timestamp > LONG_CLICK_LENGTH;
state = digitalRead(this->_pin);
if (state == LOW) {
break;
}
}
if (&this->_listener != NULL) {
if (longClicked) {
(*this->_listener).longClicked();
}
else {
(*this->_listener).clicked();
}
}
}
}
public:
Button(int pin) {
this->_pin = pin;
}
void init() {
pinMode(this->_pin, OUTPUT);
PT_INIT(&this->_thread);
}
void setListener(ButtonListener *listener) {
this->_listener = listener;
}
void listen() {
this->listenerHook(&this->_thread);
}
};
现在我创建了两个实现ButtonListener
:
class Button12Listener : public ButtonListener {
public:
void clicked() {
Serial.println("Button 12 clicked!");
}
}
另一个实现是 aButton13Listener
并打印“Button 13 clicked!”
然后让我们运行代码:
// Instantiate the buttons
Button button12(12);
Button button13(13);
void setup() {
Serial.begin(9600);
button12.init();
button13.init();
// Add listeners to the buttons
button12.setListener(new Button12Listener());
button13.setListener(new Button13Listener());
}
void loop() {
while (true) {
// Listen for button clicks
button12.listen();
button13.listen();
}
Serial.println("Loop ended.");
delay(60000);
}
我期待“点击按钮 12!” 当我单击针脚 12 上的按钮时,“单击了按钮 13!” 当我单击引脚 13 上的按钮时。
但是当我尝试点击任何按钮时,它会随机打印“Button 12 clicked!” 或“点击了按钮 13!” 无论我按什么按钮。
看起来原型线程在按钮或其他东西之间共享。
如果我检查按钮的调用顺序,如下所示:
button12.listen();
Serial.println("listen12");
button13.listen();
Serial.println("listen13");
然后是以下输出:
12
13
12
13
12
12
这似乎没问题。
所以有什么问题?我错过了什么?