#include <TM1637Display.h>
#include <Preferences.h>
#define CLK 22
#define DIO 21
#define BTN_START 18
#define BTN_RESET 19
TM1637Display display(CLK, DIO);
Preferences prefs;
bool running = false;
unsigned long lastMillis = 0;
unsigned long lastBlink = 0;
bool colonOn = true;
uint8_t hours = 0;
uint8_t minutes = 0;
void saveTime() {
prefs.begin("timer", false);
prefs.putUChar("hours", hours);
prefs.putUChar("minutes", minutes);
prefs.end();
}
void loadTime() {
prefs.begin("timer", true);
hours = prefs.getUChar("hours", 0);
minutes = prefs.getUChar("minutes", 0);
prefs.end();
if (hours > 99 || minutes > 59) {
hours = 0;
minutes = 0;
}
}
void showTime(bool colon) {
int displayTime = hours * 100 + minutes; // HHMM
uint8_t dots = colon ? 0b01000000 : 0;
display.showNumberDecEx(displayTime, dots, true);
}
void setup() {
pinMode(BTN_START, INPUT_PULLUP);
pinMode(BTN_RESET, INPUT_PULLUP);
display.setBrightness(0x0f);
loadTime();
showTime(true);
}
void loop() {
// --- Start/Stop button ---
if (digitalRead(BTN_START) == LOW) {
delay(50);
if (digitalRead(BTN_START) == LOW) {
running = !running;
if (running) {
lastBlink = millis(); // reset blink timing
colonOn = true;
} else {
saveTime();
colonOn = true; // colon steady ON when stopped
}
showTime(colonOn);
while (digitalRead(BTN_START) == LOW);
}
}
// --- Reset button ---
if (digitalRead(BTN_RESET) == LOW) {
delay(50);
if (digitalRead(BTN_RESET) == LOW) {
hours = 0;
minutes = 0;
saveTime();
colonOn = true;
showTime(true);
while (digitalRead(BTN_RESET) == LOW);
}
}
// --- Timer update every 1 min ---
if (running && millis() - lastMillis >= 60000UL) {
lastMillis += 60000UL;
minutes++;
if (minutes > 59) {
minutes = 0;
hours++;
if (hours > 99) hours = 0;
}
showTime(colonOn); // don't force colon, keep blink state
}
// --- Colon blink ---
if (running && millis() - lastBlink >= 500UL) {
lastBlink += 500UL;
colonOn = !colonOn;
showTime(colonOn);
}
}