Your First Project: A Reaction Timer Game
A complete first project combining a button, an LED, millis() timing, and the Serial Monitor — see how many milliseconds it takes you to react.
You'll need: the button wiring from Lesson ard-05 (pin 2), an LED and resistor on pin 8, and everything else this course has covered along the way.
The game: the sketch waits a random delay, lights the LED, and starts timing. You press the button as fast as you can, and the sketch reports your reaction time in milliseconds over Serial.
const int buttonPin = 2;
const int ledPin = 8;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
randomSeed(analogRead(A5)); // seed randomness from a floating pin
}
void loop() {
Serial.println("Get ready...");
delay(random(2000, 5000)); // random wait, 2-5 seconds
digitalWrite(ledPin, HIGH);
unsigned long startTime = millis();
while (digitalRead(buttonPin) == LOW) {
// wait here until the button is pressed
}
unsigned long reactionTime = millis() - startTime;
digitalWrite(ledPin, LOW);
Serial.print("Reaction time: ");
Serial.print(reactionTime);
Serial.println(" ms");
delay(2000); // pause before the next round
}
A few new pieces, each built from things you already know: random(min, max) picks a random number in that range, seeded once by randomSeed() so the sequence isn't identical every time the board resets. The while loop is new — unlike the millis()-based non-blocking pattern from Lesson ard-18, this deliberately blocks on purpose, doing nothing at all until the button becomes HIGH, which is exactly the behavior a reaction-timer needs: precise timing between the LED lighting and your press, with nothing else the sketch needs to do simultaneously.
Open the Serial Monitor, upload, and play a few rounds. As a next step, try storing each round's time in an array and printing your best result after five rounds — a natural extension using only tools this course has already covered.