Select Page

Difficulty Level = 1 [What’s this?]

How fast can you press a button once a timer starts counting? Find out by attaching a button to your Arduino and the Digit Shield. A simple tactile button switch is connected to digital pin 8 and ground.




Press the button once to start the sequence. First the Arduino will wait a random amount of time between 2 and 5 seconds, then it will start counting milliseconds on the display. As soon as you see the numbers start, press the button again to stop the count. Then repeat: press the button again to clear the display and start the random wait before the numbers start counting again.

Here is the complete code:

#include <DigitShield.h>
#define BUTTON 8

unsigned long start, stop;

void setup() {
  randomSeed(analogRead(0));

  pinMode(8, INPUT);
  digitalWrite(8, HIGH);

  DigitShield.begin();
  DigitShield.setBlank(true);
}

void loop() {
  // wait until button press
  while (digitalRead(BUTTON) == HIGH);

  // turn off the display
  DigitShield.setBlank(true);

  // delay from 2 to 5 seconds
  delay(random(2000, 5000));
  start = millis();
  DigitShield.setBlank(false);

  while (true) {
    DigitShield.setValue((int)(millis() - start));
    if (digitalRead(BUTTON) == LOW) {
      stop = millis();
      break;
    }
  }

  DigitShield.setValue((int)(stop-start));
  delay(1000);
}