Stopwatch on a 4-digit display (TM1637)
Count seconds and hundredths on a TM1637 4-digit display, with a button to start, stop and reset.
Displays · Beginner
In a real product: Sports scoreboard (Consumer electronics): A four-digit display shows the time.
Four digits of seven segments are 32 LEDs. The TM1637 chip on the display module drives them all and takes what to show over two pins, CLK and DIO, so any two digital pins will do.
What you'll learn
- Showing numbers, and the colon, on a TM1637 module
- Timing with
millis()instead ofdelay(), so the button is read while the time counts - A press-to-start, press-to-stop, long-press-to-reset button
How it works
The TM1637 speaks a two-wire protocol that looks like I²C without an address: a START, bytes sent least significant bit first with an acknowledgement after each, and a STOP. The library handles it: showNumberDecEx() turns a number into segment patterns, and its second argument lights the colon (0b01000000 is the colon between the second and third digits).
The time is millis() - started while running. Showing seconds * 100 + hundredths with the colon makes it read as SS:hh. The button uses INPUT_PULLUP, so it reads LOW while pressed.
Try this
- Press the button to start, again to stop, and hold it for a second to reset.
- Show minutes and seconds instead, for times longer than 99 seconds.
- Use
setBrightness(1)andsetBrightness(7)to see the brightness levels.
sketch.ino
// A stopwatch: press to start and stop, hold for one second to reset. Shows SS:hh on a TM1637 display.
#include <TM1637Display.h>
const int CLK = 2, DIO = 3, BUTTON = 4;
TM1637Display display(CLK, DIO);
bool running = false;
unsigned long started = 0, shown = 0, pressedAt = 0;
bool wasPressed = false;
void setup() {
pinMode(BUTTON, INPUT_PULLUP);
display.setBrightness(5);
display.showNumberDecEx(0, 0b01000000, true);
}
void loop() {
bool pressed = digitalRead(BUTTON) == LOW;
if (pressed && !wasPressed) pressedAt = millis();
if (!pressed && wasPressed) {
if (millis() - pressedAt > 1000) { running = false; shown = 0; }
else if (running) { running = false; shown = millis() - started; }
else { running = true; started = millis() - shown; }
}
wasPressed = pressed;
unsigned long t = running ? millis() - started : shown;
unsigned int seconds = (t / 1000) % 100, hundredths = (t / 10) % 100;
display.showNumberDecEx(seconds * 100 + hundredths, 0b01000000, true);
delay(10);
}