Menu
CoddyTech

Reaction Game: False Start

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

Right now a clever player can cheat: press over and over during the wait, and one of the presses lands just after the light. Races have a rule for this: moving before the signal is a false start, and the start is cancelled.

The state machine already knows when the player is too early: any press in the WAITING state. Look for it there, before checking the clock:

case WAITING:
  if (pressed) {
    Serial.println("Too soon!");
    state = READY;
  } else if (millis() - waitStart >= waitTime) {
    // light the LED, as before
  }
  break;

Going back to READY ends the round: the LED never lights, and the next press starts a new game with a new random wait. With delay(waitTime) the board could not see this press at all.

challenge icon

Challenge

Medium

Catch false starts:

  • in WAITING, a press prints Too soon! and goes back to READY without lighting the LED
  • everything else stays as it is: the next press starts a new round

Press Run, try pressing twice quickly, 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
unsigned long litAt = 0;     // when the LED came on

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);
        litAt = now;
        state = LIT;
      }
      break;
    case LIT:
      if (pressed) {
        digitalWrite(ledPin, LOW);
        unsigned long reaction = now - litAt;
        Serial.print("Reaction: ");
        Serial.print(reaction);
        Serial.println(" ms");
        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