首页 > 解决方案 > 如何在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;

标签: arduinoarduino-unoarduino-idearduino-c++

解决方案


推荐阅读