I am a new user to the Arduino but I do have basic electronics and programming knowledge, I have studied C++, Java and PHP many years ago although forgotten most of it now!
I am writing a basic hand loop game out of an old coat hanger. I thought it would be really simple. The coat hanger is just a switch which is connected to a pin setup as an input on the Arduino.
I then setup a variable called lives, each time the switch is triggered I set the lives detract by 1.
It works perfectly if I just want to change the colour of an LED, (one colour each for live) and of course once the lives run out, setting the lives back to 4 resets the game.
My problem is what I actually want to do is make the LEDs flash via a for loop for a few seconds before the LED changes colour, I’ve also added a small delay to make sure the user has enough time to start the next life.
My problem is the IF statement keeps repeating itself as it is in a loop for example the code inside this if statement runs in a loop until another live is not and lives=1 etc. I only want the tone and the LED flash sequence to run 5 times, and then the amber LED will light up until the next condition occurs. Instead it runs continuously until another life is lost.
else if (lives == 2) {
for (int i=0; i <= 5; i++){
digitalWrite(greenPin, HIGH);
digitalWrite(redPin, LOW);
digitalWrite(amberPin, LOW);
delay(25);
digitalWrite(greenPin, LOW);
digitalWrite(redPin, LOW);
digitalWrite(amberPin, HIGH);
delay(25);
digitalWrite(greenPin, LOW);
digitalWrite(redPin, HIGH);
digitalWrite(amberPin, LOW);
delay(250);
tone (8, 150, 200);
}
digitalWrite(amberPin, HIGH);
digitalWrite(greenPin, LOW);
digitalWrite(redPin, LOW);
}
So to put it simply, even the condition lives=2 may exist for a long time, I only want the sequence of events to happen once, not continuously until the variable lives changes.
Am I being very thick here and missed something very obvious?
Thanks :).