My intention is to ask some questions, if the answer is right, a green light will light up, if it is wrong, a red light will turn on. But the code does not work as expected, because the 'while' code
don't give me answers. Please help me, I'm a beginner, the code is below. This is my first code.
#define led_green 4
#define led_red 8
int response;
int response2;
/*
int resposta3;
int resposta4;
int resposta5;*/
void setup() {
pinMode(led_green, OUTPUT);
pinMode(led_red, OUTPUT);
Serial.begin(9600);
//question1//
Serial.println("How much is 4+4?");
Serial.println("type below:");
while(!Serial.available()){}
if (Serial.available()){
response=Serial.read();
if(response=='8'){
Serial.println("Response Correct");
digitalWrite(led_green, HIGH);
delay(3000);
digitalWrite(led_green, LOW);
}
else {
Serial.println("Response Incorrect");
digitalWrite(led_red, HIGH);
delay(3000);
digitalWrite(led_red, LOW);
}}
//question2//
Serial.println("How Much is 50-17?");
Serial.println("type below:");
while(Serial.available()){delay(2000);}
if(Serial.available()){
response2=Serial.read();
if (response2 == '33'){
Serial.println("Response Correct");
digitalWrite(led_green, HIGH);
delay(3000);
digitalWrite(led_green, LOW);
}
else {
Serial.println("Response Incorrect");
digitalWrite(led_red, HIGH);
delay(3000);
digitalWrite(led_red, LOW);
}}
}
void loop() {
}
Please edit your post, select all code and apply code tags using the <CODE\> button; next save your post. It makes it easier to read, easier to copy and the forum software will not think that your code are formatting instructions.
I suspect that the line-ending setting in serial monitor play a role.
'33' isn't a single character? You need to read and compare things differently for multiple-byte answers.
Serial.read() only reads one byte from the input stream:
If the user hasn't provided any Serial input in the miniscule time since the prompt, Serial.available() will be false and it will quickly drop through.
Also '8' is not an int. It is a char.
And 33 needs double quotes ("33") as it is a string of char.
I recommend to read on arrays or maybe even arrays of structs. That way you can iterate through all your questions instead of copy paste code...
My question is simple, what is 4+4, if the person answers 8 a message will appear saying that it is correct, if they answer anything else it will appear that the message is incorrect, using the if and else if codes, but the while in the second question is endlessly waiting for something to be typed, even if it has already been typed.
Oh, this is worse than I thought -- if there is serial in the buffer, such as the enter key after the '8', Serial.available() will remain true and this while loop will repeat delay(2000) forever.
Who is going to tell him to move the "serial stuff" from the setup function (the one that only runs once per startup) into the loop function (the one that continuously loops)? 1, 2 , 3 Not it!