gpt4 book ai didi

c - Arduino 无法读取按钮

转载 作者:行者123 更新时间:2023-11-30 15:44:24 25 4
gpt4 key购买 nike

该程序的目的是计算按下按钮 1 的次数,然后按下按钮 2 打破循环。 Button2 就像一个回车键。

如果我在没有 do while 的情况下单独运行 do while 语句中的内容,它将对每个按钮按下的次数进行计数。我用它来验证我是否正确构建了电路。但由于某种未知的原因,如果我将相同的代码放入 do while 或只是一会儿,那么它不会读取引脚。它将在 do while 内循环,但永远不会在最后退出到 did 语句。如果我在按下两个按钮中的任何一个时启动arduino,那么它会记录正在按下一个按钮,但是一旦我放开它,它就不会再执行任何操作。请告诉我我做错了什么。

我的代码

int ledpin = 11;
int button1pin = 7;
int button2pin = 2;
int button1counter = 0;
int button1state = 0;
int lastButton1state = 0;
int button2state = 0;
int lastButton2state = 0;
int button2counter = 0;

void setup() {
// initialize the digital pin as an output.
pinMode(button1pin, INPUT);
pinMode(button2pin, INPUT);
Serial.begin(9600);
}

void loop() {
button1state = digitalRead(button1pin);
button2state = digitalRead(button2pin);
do {
if (button1state != lastButton1state) {
if (button1state == HIGH) {
button1counter++;
Serial.print("number of button 1 pushes: ");
Serial.println(button1counter);
}
lastButton1state = button1state;
}
} while(button2state == LOW);



Serial.println("done");


}

谢谢我改变了它,当然你的权利。但是,我不太明白为什么你是对的。我用我的理解来注释一下代码,如有错误请指正。

void setup() {                

pinMode(button1pin, INPUT);//tells comp to make button 1 input
pinMode(button2pin, INPUT);//tells comp to make button 2 input
Serial.begin(9600);
}

void loop() {
button1state = digitalRead(button1pin);//tells comp to begin reading pin? but for how long?
button2state = digitalRead(button2pin);
do {

最佳答案

您在 while 循环之外读取按钮状态,因此您的button1state和button2state永远不会更新,这就是为什么您进入无限循环只需做一点点改变:

void loop() {
do {
button1state = digitalRead(button1pin);
button2state = digitalRead(button2pin);

if (button1state != lastButton1state) {
if (button1state == HIGH) {
button1counter++;
Serial.print("number of button 1 pushes: ");
Serial.println(button1counter);
}
lastButton1state = button1state;
}
} while(button2state == LOW);

Serial.println("done");


}

关于c - Arduino 无法读取按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com