Hi,
I'm having a little trouble getting this to do what I want it to do...
It's a game with 5 lights and the player is supposed to push a button when the middle LED lights up. Right now, I can't get it to detect the button push unless I hold it. I think I know where the problem is, but my coding level isn't good enough to fix it.
for (int x = 4; x<=12; x=x+2)
{
digitalWrite(x, HIGH);
delay(wait);
if (digitalRead(ButtonPin) == LOW) //BUTTON PUSHED
In this section, I'm assuming the delay prevents it from detecting any button press. Any suggestions?
Here is the whole code
int ButtonPin = 2;
int pin= 4; // declares LEDs
int pin1= 6;
int pin2= 8;
int pin3= 10;
int pin4= 12;
int wait= 1000; // this will be used for delays
int score = 0; // this will tell you how many times you got it
int wrong = 0; // if your wrong too many times the game starts over
void setup ()
{
pinMode(pin, OUTPUT); // sets as output
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);
pinMode(pin4, OUTPUT);
pinMode(ButtonPin, INPUT_PULLUP);// sets as input
Serial.begin(9600);
}
void loop ()
{
while (digitalRead(ButtonPin) == HIGH) //Beginnning of the game
{
int wrong = 0;
while(wrong!=5) //runs down the row & lights up the LEDS - start
{
for (int x = 4; x<=12; x=x+2)
{
digitalWrite(x, HIGH);
delay(wait);
if (digitalRead(ButtonPin) == LOW) //BUTTON PUSHED
{
if (x == 8) //if you pushed the button and you were at 'red' light
{
delay(2000);
BlinkLED(); // USER GOT IT RIGHT
score= score+1;
Serial.println("Your Score:");
Serial.println(score);
wait = wait*.9; //decreases the time which led moves to another one -- therefore led getting faster
}
else
{
digitalWrite(x, LOW);
wrong= wrong+1; // the wrong count increase
Serial.println("You got it wrong");
Serial.println(wrong);
digitalWrite(4,HIGH); // signifies to the user that she/he is wrong - temporary signal - going to change this later
digitalWrite(12,HIGH);
digitalWrite(4,LOW);
digitalWrite(12,LOW);
wait = wait*.9;
if (wrong == 5) // if you get 5 wrong
{
for (int x = 4; x<=12; x=x+2)
{
digitalWrite(x, HIGH); // all lights will come on
delay(100);
}
for (int x = 12; x>=4; x=x-2)
{
digitalWrite(x, HIGH);
delay(100);
}
wrong = 0; // resets wrong count
score = 0; // resests score
wait = 1000; // resets delay time
}
}
}
digitalWrite(x,LOW);
}
}
}
}
void BlinkLED() // SIGNIFIES THAT THE USER IS CORRECT
{
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
digitalWrite(4, HIGH);
digitalWrite(4, LOW);
}