Menu
CoddyTech

Button Stopwatch

Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 18 of 18.

A stopwatch has two states, running and stopped, and a press moves it from one to the other. It measures time the safe way: store millis() at the start, subtract at the end.

if (!running) {
  running = true;
  startTime = millis();
} else {
  running = false;
  Serial.println(millis() - startTime);
}

The button is debounced as it was for the mode button: act when the reading changes, then wait 20 ms. Both presses wait the same 20 ms, so the time between them stays right.

The LED shows the state: on while the stopwatch runs.

challenge icon

Challenge

Medium

The button is already read and debounced, and onPress() runs once for each press. Write onPress():

  • if the stopwatch is not running: start it, store millis() in startTime and light the LED
  • if it is running: stop it, turn the LED off and print the time in milliseconds

Press Run, press the button twice, then Check.

Try it yourself

const int ledPin = 13;
const int buttonPin = 2;

bool wasPressed = false;
bool running = false;
unsigned long startTime = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
}

// Called once for each press.
void onPress() {
  // not running: start, remember the time, light the LED
  // running: stop, turn the LED off, print the time in ms
}

void loop() {
  bool pressed = digitalRead(buttonPin) == LOW;
  if (pressed != wasPressed) {
    if (pressed) {
      onPress();
    }
    wasPressed = pressed;
    delay(20);   // let the contacts settle
  }
}
quiz iconTest yourself

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

All lessons in Timing Without Delay

Practice on your own: Arduino playground