so I need to make a arduino program, generates 2 random numbers, makes a + calculation with them and asks user the right answer. If the answer is right AKA Calculation==User Answer, then led is set to LOW, and serialprint sent. If its wrong, Led lights up and serialprint sent again. It works if i set the variables manually etc. But the I think the problem is with my serialRead, somehow it doesnt set the value it got from the user as the value of the variable (Luku4)
Here is the code, I hope you can help me.
int Luku1 = 0;
int Luku2 = 0;
int Luku3 = 0; //Summa
int Luku4 = 0; //Vastaus
const int ledPin = 13;
byte i = 0;
void setup() {
for (i=0; i<4; i++){
pinMode(ledPin, OUTPUT);
}
randomSeed(analogRead(0));
Serial.begin(9600);
Serial.println("Arvotaan 2 satunnaislukua ja summataan ne yhteen. Kerro oikea vastaus");
}
void loop() {
Serial.println("Arvotaan 2 satunnaislukua");
Luku1 = random(1,5);
Luku2 = random(1,5);
Serial.println(Luku1);
Serial.println("+");
Serial.println(Luku2);
Luku3 = Luku1 + Luku2;
delay(100);
Serial.println("Mika on vastaus?");
Luku4 = Serial.read();
while(Serial.available() == 0){}
if (Luku4==Luku3) {
digitalWrite(ledPin, LOW);
Serial.println("Oikea vastaus");
delay(2000);
}
else{
digitalWrite(ledPin, HIGH);
Serial.println("Vaarin");
delay(2000);
digitalWrite(ledPin, LOW);
}
}
Serial.read
to after the "wait for serial input"-line. Secondly.Serial.read
will return a character, not a number. So you have to convert the ascii value of the letters "0"-"9" to the integer value of 0-9. This can be done by subtracting 48, as "0" is ascii code nr 48.