Menu
CoddyTech

Reaction Game: Timer

Part of the Projects section of Coddy's Arduino journey. Lesson 6 of 24.

Now the game measures you. The reaction time is the time from the LED lighting to your press, so the sketch needs to remember one moment: when it lit the LED.

digitalWrite(ledPin, HIGH);
litAt = millis();
state = LIT;

When the press comes in the LIT state, the difference is the answer:

unsigned long reaction = millis() - litAt;
Serial.print("Reaction: ");
Serial.print(reaction);
Serial.println(" ms");

This only works because the sketch never sits in a delay(): loop() checks the button thousands of times every millisecond, so the press is seen less than a millisecond after it happens. Most people need 200 to 300 ms.

challenge icon

Challenge

Medium

Time the player:

  • save millis() in litAt when the LED lights
  • when the press comes in LIT, work out millis() - litAt
  • print it as Reaction: 250 ms

Press Run, play, read the Serial monitor, 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;
  unsigned long now = millis();

  switch (state) {
    case READY:
      if (pressed) {
        randomSeed(micros());  // the press time is never the same twice
        waitTime = random(1000, 3001);
        waitStart = now;
        state = WAITING;
      }
      break;
    case WAITING:
      if (now - waitStart >= waitTime) {
        digitalWrite(ledPin, HIGH);
        state = LIT;
      }
      break;
    case LIT:
      if (pressed) {
        digitalWrite(ledPin, LOW);
        state = READY;
      }
      break;
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Projects

Practice on your own: Arduino playground