问题描述
我正在尝试使用 arduino,并为一些带有状态开关的按钮编程.如果它是on",那么它就会off",反之亦然.
I'm trying out arduino and have programmed some button with a state switch. If it was "on" then it turns "off" and versa.
#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);
但它不起作用!
It works well, but weird thing is that when i was programming i added some Serial prints to monitor output thru COM. Then after it all worked well i wanted to eliminate Serial.println(a);
but it doesn't work then!
循环根本不响应我按下的按钮.我错过了什么吗?什么会导致这种事情?也许我错过了一些东西,所以新鲜的眼光会很棒:)
The loop doesn't respond to my button pressing at all.Am I missing something? What could cause this kind of thing ?Maybe i missed something, so fresh eye would be great : )
非常感谢!
推荐答案
您正在通过调用 digitalRead(push1.read())
读取按钮的状态.
You are reading the state of the button by calling digitalRead(push1.read())
.
这几乎肯定是不正确的(但我没有使用 Bounce 库).push1.read()
正在读取按钮的状态,大概是高 (0x1) 或低 (0x0).然后,此按钮状态值将用作在 digitalRead
调用中读取的引脚.因此,在我看来,您正在阅读引脚 0 或 1 的状态,而不是按钮所在的引脚 2.如果我没记错的话,引脚 0 和 1 是硬件串行端口.
This is almost certainly incorrect (but I haven't used the Bounce library). push1.read()
is reading the state of the button, presumably HIGH (0x1) or LOW (0x0). This button state value is then being used as the pin to read in the call to digitalRead
. So, it looks to me like you are reading the state of either pin 0 or 1, not pin 2 where the button is. If I remember correctly pins 0 and 1 are the hardware serial port.
变化:
int x = digitalRead(push1.read());
到:
int x = push1.read();
看看是否效果更好.
我怀疑 Serial.println(a)
是一个红鲱鱼,它肯定会起到延迟的作用.串行端口和您的代码之间可能会发生奇怪的交互,因为我相信您是从串行端口而不是按钮读取按钮状态"(x
).
I suspect the Serial.println(a)
is a red-herring, it would certainly be acting as a delay. There may be a weird interaction happening between the serial port and your code as I believe you are reading the "button state" (x
) from the serial port not the button.
这篇关于Arduino Serial.println 奇怪的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!