我正在尝试使用arduino并使用状态开关编程了一些按钮。如果它“开启”则会“关闭”,反之亦然。
#include <Bounce.h>
const int buttonPin = 2;
const int ledPin = 6;
int ledState = HIGH;
int a = LOW;
int b = LOW;
Bounce push1 = Bounce( buttonPin,5 );
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
push1.update ( );
int x = digitalRead(push1.read());
if (x != b) {
if (x == HIGH) {
if (a == HIGH) {
a = LOW;
}
else {
a = HIGH;
}
}
else {
}
}
digitalWrite(ledPin, a);
Serial.println(a); // Weird thing
b = x;
}
它运作良好,但奇怪的是,当我编程时,我添加了一些串行打印来监视通过COM的输出。然后在一切运作良好之后我想要消除Serial.println(a);
但它不起作用!
循环完全没有响应我按下的按钮。 我错过了什么吗?什么可能导致这种事情? 也许我错过了一些东西,所以新鲜的眼睛会很棒:)
非常感谢!
答案 0 :(得分:2)
您正在通过调用digitalRead(push1.read())
来阅读按钮的状态。
这几乎肯定不正确(但我没有使用Bounce库)。 push1.read()
正在读取按钮的状态,可能是HIGH(0x1)或LOW(0x0)。然后,此按钮状态值将用作读取digitalRead
调用的引脚。因此,在我看来,你正在读取引脚0或1的状态,而不是按钮所在的引脚2。如果我没记错,引脚0和1是硬件串口。
变化:
int x = digitalRead(push1.read());
到:
int x = push1.read();
看看它是否更好。
我怀疑Serial.println(a)
是一只红鲱鱼,它肯定会起到延迟的作用。串行端口和代码之间可能会发生奇怪的交互,因为我相信您正在从串口而不是按钮读取“按钮状态”(x
)。
答案 1 :(得分:1)
mttrb是正确的
int x = digitalRead(push1.read());
是问题的根源。人们可以在Arduino's web page of the library看到,其示例最初可能会错过领先。
digitalWrite(LED, bouncer.read());
值得注意的是
int x = push1.read();
根据库代码,只需定期读取数字读取(buttonPin);没有太多真正的好处。
通常更有利的地方if (push1.fallingEdge()) {
...
注意到falling / risingEdge()函数是有状态的,并且这些成员函数清除状态转换。这样就可以相应地标记新边缘以供阅读。