此程序用于计算按钮1按下的次数,然后按下按钮2按钮退出循环。 button2就像一个回车键。
如果我在没有do的情况下单独执行do while语句内部的操作,那么它会计算每个按钮的推送次数。我用它来验证我是否正确构建了电路。但由于某些未知原因,如果我将相同的代码放入do或者只是一段时间,那么它就不会读取引脚。它将在do while内循环,但最后不会退出到done语句。如果我在按下两个按钮中的任何一个时启动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 {
答案 0 :(得分:1)
你在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");
}