ATmega328P/A build/33. Build: a reaction timer
A build · 33 of 33

Build: a reaction timer

The pin-13 lamp (L on the UNO, D13 on the Nano) lights after a wait you cannot predict, and you touch a wire from D2 to GND as fast as you can. The board times it to a few microseconds, calls a foul on an early touch, and keeps your best time through a power cut. It needs the board and one jumper wire.

Your board

What you need

The board, the USB-C cable and one jumper wire (a straightened paper clip works). The wire goes in D2, on the top-right strip. Its other end stays loose in your hand. The target is the GND hole beside 13 on the top-left strip.

D2 is set to INPUT_PULLUP before anything else happens, so a wire from it to GND is always safe: the INPUT_PULLUP article has the mechanism. The pin reads HIGH while the wire is loose and LOW while it touches GND.

One round

One round, on a time line
a fair round
The round
Time
0 s
L lamp
off
Lockout after each touch
50 ms
D2 rests HIGH on its pull-up. Touching the wire to GND pulls it LOW, and the interrupt notes the time of the first falling edge.

A round starts with a touch, so you choose when to begin. The sketch then waits a random 1 to 4 seconds, lights the lamp, and times how long you take to touch GND again. A touch during the wait is a foul and the round starts over.

The random wait needs a random seed, or random() gives the same sequence after every reset. The sketch uses the moment you touched GND to start, measured in microseconds, which nobody can repeat on purpose.

Timing the touch

The touch is caught by an interrupt on D2, INT0, set to fire on the falling edge. The interrupt routine does one thing: if no touch has been recorded yet, it saves micros() and sets a flag. Then it ignores every later edge, which is how the bounce of a wire meeting metal (the bounce article shows it) cannot move the time. The first edge is the touch.

The reaction time is that saved value minus the micros() reading taken just after the lamp lit. On a 16 MHz board, micros() counts in steps of 4 µs (Arduino's reference), far finer than any hand. The result is rounded to milliseconds for printing.

The lockout

The flag is only cleared once D2 has stayed HIGH for 50 ms without a break. waitForRelease() does it, and it runs after every touch. Without it, the bounce as you lift the wire would set the flag again, and the next wait would end in a foul you never made. The waits use millis() in a loop rather than delay(), so the sketch can see a foul the moment it happens; the millis() article has the pattern.

The best time survives a power cut

The best time lives in EEPROM, at address 0, as a small record: two marker bytes and the time. The marker tells this sketch's record apart from whatever an earlier sketch left there. A chip whose EEPROM has never been written reads 0xFF in every byte, which does not match the marker, so the first run starts with no best time.

The sketch writes only when you beat your best, never on an ordinary round. Each EEPROM cell is rated for 100,000 writes (Microchip's datasheet), which a game writing only records will never reach. Holding the wire on GND while you press reset clears the record.

The code

Reaction_Timer.ino

Put one jumper wire in the D2 hole and leave its other end loose. Upload, open the Serial Monitor at 9600 baud, and touch the loose end to a GND hole to start a round. When the pin-13 lamp lights, touch GND again as fast as you can.

// Reaction_Timer.ino — the pin-13 lamp lights after a random
//   wait; touch GND fast
// Tools > Board: Arduino Uno, or Arduino Nano with
//   Processor ATmega328P (Old Bootloader if the upload says
//   "not in sync")
// Tools > Port: the CH340 port
// Serial Monitor: 9600 baud
// Wiring: one jumper wire in D2, its other end loose. D2 is
//         INPUT_PULLUP, so the loose end may touch GND safely.
//         Touch it to a GND hole to play.
// Hold the wire on GND while you press reset: the best time
// is cleared.
#include <EEPROM.h>

const byte TOUCH = 2;                 // INT0
const byte LAMP = 13;                 // L on UNO, D13 on Nano
const unsigned long LOCKOUT_MS = 50;  // HIGH this long = let go
const unsigned long TIMEOUT_MS = 5000;
const unsigned int MARKER = 0xBE57;   // "this is our record"

struct Record {
  unsigned int marker;
  unsigned long bestMs;               // 0 = no best yet
};
Record rec;

volatile bool touched = false;
volatile unsigned long touchedAt = 0; // micros() at the edge

void onTouch() {
  if (!touched) {                     // only the first edge
    touchedAt = micros();
    touched = true;
  }
}

// Wait until D2 has stayed HIGH for LOCKOUT_MS, then re-arm.
// The bounce of letting go never reaches the next round.
void waitForRelease() {
  unsigned long highSince = millis();
  while (millis() - highSince < LOCKOUT_MS) {
    if (digitalRead(TOUCH) == LOW) highSince = millis();
  }
  touched = false;
}

void setup() {
  Serial.begin(9600);
  pinMode(TOUCH, INPUT_PULLUP);
  pinMode(LAMP, OUTPUT);

  EEPROM.get(0, rec);
  if (rec.marker != MARKER || digitalRead(TOUCH) == LOW) {
    rec.marker = MARKER;
    rec.bestMs = 0;
    EEPROM.put(0, rec);
    Serial.println(F("Best time cleared."));
  }
  attachInterrupt(digitalPinToInterrupt(TOUCH), onTouch, FALLING);
}

void loop() {
  waitForRelease();
  Serial.println(F("Touch GND to start."));
  while (!touched) {}
  randomSeed(touchedAt);              // your timing is the dice
  waitForRelease();

  unsigned long wait = random(1000, 4001);   // 1 to 4 s
  unsigned long start = millis();
  while (millis() - start < wait) {
    if (touched) {
      Serial.println(F("Too soon. Foul."));
      return;                         // loop() starts again
    }
  }

  digitalWrite(LAMP, HIGH);
  unsigned long litAt = micros();
  while (!touched) {
    if (micros() - litAt > TIMEOUT_MS * 1000UL) {
      digitalWrite(LAMP, LOW);
      Serial.println(F("No touch in 5 s."));
      return;
    }
  }
  digitalWrite(LAMP, LOW);

  // touched is true, so the interrupt will not change
  // touchedAt again until waitForRelease() clears it.
  long us = (long)(touchedAt - litAt);
  if (us < 0) {                       // touched as it lit
    Serial.println(F("Too soon. Foul."));
    return;
  }
  unsigned long ms = (us + 500) / 1000;
  Serial.print(F("Reaction: "));
  Serial.print(ms);
  Serial.println(F(" ms"));

  if (rec.bestMs == 0 || ms < rec.bestMs) {
    rec.bestMs = ms;
    EEPROM.put(0, rec);               // only a new best is written
    Serial.print(F("New best: "));
  } else {
    Serial.print(F("Best: "));
  }
  Serial.print(rec.bestMs);
  Serial.println(F(" ms"));
}

D2 is INPUT_PULLUP, so the loose end can touch GND as often as you like. To clear the best time, hold the wire on GND and press the reset button.

When it does not work

Every round is a foul, even when I wait for the lamp

The wire is resting against GND, and D2 never goes back HIGH. Hold the loose end clear of the board between touches. The round only starts once D2 has stayed HIGH for 50 ms.

Touch GND to start never appears

The sketch prints it only once D2 is HIGH and settled, so a wire stuck on GND holds it back. Check the Serial Monitor is at 9600 baud, then lift the wire. Opening the monitor resets the board, so the line appears straight after.

The best time is a number I never scored

Another sketch wrote to EEPROM address 0 with the same two marker bytes, which is unlikely but possible. Hold the wire on GND and press reset: the sketch clears the record and starts again.

Times of 0 or 1 ms

The wire touched GND at the same instant the lamp lit, or was already touching and bounced. The sketch calls a touch before the lamp a foul, but one inside the same few microseconds can slip through. Lift the wire fully between rounds.

Where this goes next

The book ends here. The fundamentals courses explain the electricity and the buses underneath it: pull-ups, UART, I2C, SPI and power.

Fundamentals →

Edit this page — content/books/atmega328p/a-reaction-timer.mdx

Discuss this article

Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.

Browse Modules and blocks on the forum →