Menu
CoddyTech

Reaction Game: Best Time

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

The sketch keeps the best (lowest) time in a variable and prints it after every round.

At the start there is no best time yet. Use a value no real round can have, 0, to mean "none yet". After each round: if there is no best yet, or this round beat it, this round is the new best.

if (best == 0 || reaction < best) {
  best = reaction;
}
Serial.print("Best: ");
Serial.print(best);
Serial.println(" ms");

Put this in the LIT state, where a round ends with a real time. A false start never reaches that code, so it never becomes the record.

The best time lives in the board's memory (RAM), which is cleared when the power goes off: the record lasts until you press Run again.

challenge icon

Challenge

Medium

Keep a record:

  • a variable best, 0 at the start
  • after each timed round, if best is 0 or the round was faster, save the round as the new best
  • print it after every round as Best: 250 ms
  • false starts change nothing

Press Run, try to beat your best, 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 (pressed) {
        // Pressed before the light: a false start.
        Serial.println("Too soon!");
        state = READY;
      } else 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