Reaction Game: Random Wait
Part of the Projects section of Coddy's Arduino journey. Lesson 5 of 24.
The next project is a reaction game. You press the button, the board waits, then lights the LED, and you press again as fast as you can.
The wait is random, or you would learn the rhythm. random(1000, 3001) gives a whole number from 1000 to 3000.
random() is a calculation: after every power-on it gives the same numbers in the same order. randomSeed() picks where that sequence starts. Seed it with the moment of the press, in microseconds, which is different every game:
randomSeed(micros());
waitTime = random(1000, 3001);The game is a state machine with three states: READY (waiting for a press), WAITING (the random wait) and LIT (the LED is on). The wait uses millis(), so later steps can watch the button during it.
The starter already works out pressed: the button reads LOW now and read HIGH last time. This button does not bounce, so it needs no debounce.
Challenge
MediumThe button is on pin 2 and the LED on pin 12. Fill in the three states:
READY: a press seeds withmicros(), picks a wait of 1000 to 3000 ms, saves the start time, moves toWAITINGWAITING: when the wait is over, light the LED and move toLITLIT: a press turns the LED off and moves toREADY
Press Run, play a few rounds, then Check.
Try it yourself
const int ledPin = 12;
const int buttonPin = 2;
// The three states of a round
enum State { READY, WAITING, LIT };
State state = READY;
int lastButton = HIGH; // the button reading the last time
unsigned long waitStart = 0; // when the wait began
unsigned long waitTime = 0; // how long this wait lasts
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
Serial.println("Press the button to start");
}
void loop() {
int button = digitalRead(buttonPin);
bool pressed = (button == LOW && lastButton == HIGH); // pressed just now
lastButton = button;
// READY: a press starts the wait
// WAITING: when the wait is over, light the LED
// LIT: a press turns the LED off and the game is ready again
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Projects
2Reaction Game
Reaction Game: Random WaitReaction Game: TimerReaction Game: False StartReaction Game: Best TimePractice on your own: Arduino playground