I modified the “Reaction Tester” tutorial to be more like a game.
The object is to press the button (D12) when led 6 is lit.
If hit, it displays a win flash pattern (all led’s).
If you miss, it displays a red light.
The game begins at a slow speed (250) and increases to faster levels every successive hit on led 6.
The game keeps score of successive hits and displays the total number (blue flashes) after the first miss.
It then resents the game level and begins again.
The problem is
I had to change the line:
if (digitalRead(2) == HIGH)
to
if (digitalRead(2) == LOW)
to get it to run. Otherwise it hung on led4.
I can’t figure out why this change (HIGH to LOW) works.
HELP!
…Code below…
int led = 4;
int num = 0;
int score = 0;
int speed = 250;
void setup()
{
// Set the button and switch as INPUTs:
pinMode(12, INPUT);
// Set LEDs as outputs:
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
}
void loop()
{
if (digitalRead(12) == LOW) // If the button is pressed?? >>>THIS IS THE LINE I CANT FIGURE OUT<<<
{
if (led == 6) // checks if led 6 is hit
{
num = 0; // sets counter for “win” signal
while(num < 10)
{
digitalWrite(4, HIGH); // flashes the “win” signal
digitalWrite(8, HIGH);
delay(50);
digitalWrite(4, LOW);
digitalWrite(8, LOW);
delay(50);
digitalWrite(5, HIGH);
digitalWrite(7, HIGH);
delay(50);
digitalWrite(5, LOW);
digitalWrite(7, LOW);
delay(50);
num++;
}
speed = speed -50; // increases speed for next level
score = score + 1; // records score
}
else
{
analogWrite(9, 255); //flashes the “wrong” signal
delay(1200);
analogWrite(9, 0);
delay(1200);
speed = 250; // resets the speed
while (score > 0)
{
analogWrite(11, 255); // displays the score
delay(300);
analogWrite(11, 0);
delay(300);
score = score - 1;
}
}
digitalWrite(led, HIGH); // Turn the active LED on, nothing else.
}
else // Otherwise, if the button is released >>THIS ELSE IS PART OF THE FIRST IF<<
{
digitalWrite(led, LOW); // Turn the active LED off.
led = led + 1; // Increment the led variable by 1
if (led > 8) // If led is out of our range (4-8)
{
led = 4; // Set it back to the bottom (LED 4).
}
digitalWrite(led, HIGH); // Turn on the new LED
delay(speed); // Delay for speed ms.
}
// The else statement above will take up the majority of the loop() if the
// button is released. One LED will turn off, the next will turn on, and
// a short delay will occur before we loop back.
}