arduino - 如何在Arduino的while循环中使用按钮?
问题描述
所以我试着做一个小测验,它可以使用很多改进,但我想在我改进它之前有一个完成的项目。我希望用户通过按下按钮来选择答案。
我的代码目前看起来像这样。
char serialData;
int i = 1;
int redLed = 12;
int greenLed=13;
int buttonA=11;
int buttonB=10;
int buttonC=9;
int lastState = LOW;
int currentState;
void setup()
{
Serial.begin(9600);
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(buttonA,INPUT);
pinMode(buttonB,INPUT);
pinMode(buttonC,INPUT);
// read the state of the switch/button:
currentState = digitalRead(buttonA);
if(lastState == HIGH && currentState == LOW)
Serial.println("A");
// save the the last state
lastState = currentState;
delay(100);
}
void loop()
{
vraag1();
delay(1000);
vraag2();
delay(1000);
vraag3();
delay(1000);
vraag4();
delay(1000);
vraag5();
delay(1000);
vraag6();
}
void vraag1()
{ //1
Serial.println(" 3+3=? ");
delay(400);
Serial.println(" A) 6");
delay(200);
Serial.println(" B) 5 ");
delay(200);
Serial.println(" C) 4 ");
delay(200);
while (Serial.available() ==0){} //2-2
/*
This is the part I added to resolve the issue - but it
does not work.
*/
currentState = digitalRead(buttonA);
if(lastState == HIGH && currentState == LOW)
Serial.println("A");
lastState = currentState;
if (Serial.available())
{ //3
serialData = Serial.read();
if (serialData == '6' || serialData == 'a' || serialData == 'A')
{ //4
Serial.println(" Correct ");
i++;
digitalWrite(greenLed, HIGH);
} //4
else
{ //5
Serial.println(" Incorrect ");
digitalWrite(redLed, HIGH);
} //5
}
delay(1000);
digitalWrite(redLed, LOW);
digitalWrite(greenLed, LOW);
}
这是我添加尝试的代码,但它根本不起作用。有人有其他建议吗?
currentState = digitalRead(buttonA);
if(lastState == HIGH && currentState == LOW)
Serial.println("A");
lastState = currentState;
解决方案
推荐阅读
- javascript - 在 NodeJS 中不使用换行符进行日志记录
- python - 如何使用 Scapy 实现 ARP ping?
- firebase - Firestore:有没有办法获取所有集合文档及其子集合文档
- php - WooCommerce 在注册后重定向到我的帐户而不是结帐
- puppet - 使用节点默认中的类运行 Puppet Agent 时出错
- html - 从不同组件使用时,表格行不会在列中拆分
- weblogic - Weblogic 托管服务器在集群中相互进行内部通信
- ios - 如何在 iOS 13 / Safari 中禁用动量滚动?
- build - 在实时更新角度构建时出现一些错误
- matlab - 如何在Matlab中获取除第一个元素之外的矩阵的所有元素?