#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClib.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
RTC_DS3231 rtc;
// Кнопки
const int startBtn = 2;
const int resetBtn = 3;
bool running = false;
unsigned long startTime = 0;
unsigned long stopwatchTime = 0;
void setup() {
Wire.begin();
lcd.init();
lcd.backlight();
pinMode(startBtn, INPUT_PULLUP);
pinMode(resetBtn, INPUT_PULLUP);
if (!rtc.begin()) {
lcd.print("RTC not found!");
while (1);
}
// ❗ Постав час ОДИН РАЗ, потім закоментуй
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
void loop() {
// ---------------------------
// 1) Читання часу з RTC
// ---------------------------
DateTime now = rtc.now();
char buffer1[21];
sprintf(buffer1, "%02d.%02d.%02d %02d:%02d:%02d",
now.day(), now.month(), now.year() % 100,
now.hour(), now.minute(), now.second());
lcd.setCursor(0, 0);
lcd.print(buffer1);
// ---------------------------
// 2) Обробка кнопок
// ---------------------------
if (!digitalRead(startBtn)) {
delay(200); // антидребезг
running = !running;
if (running) {
startTime = millis() - stopwatchTime;
}
}
if (!digitalRead(resetBtn)) {
delay(200);
stopwatchTime = 0;
running = false;
}
// ---------------------------
// 3) Логіка секундоміра
// ---------------------------
if (running) {
stopwatchTime = millis() - startTime;
}
// секундомір: хвилини.секунди.соті
unsigned long totalMs = stopwatchTime;
int minutes = totalMs / 60000;
int seconds = (totalMs / 1000) % 60;
int centiseconds = (totalMs % 1000) / 10; // 0–99
char buffer2[21];
sprintf(buffer2, "Timer: %02d:%02d.%02d", minutes, seconds, centiseconds);
lcd.setCursor(0, 1);
lcd.print(buffer2);
delay(20);
}