#include <LiquidCrystal.h>
LiquidCrystal lcd(7,6,5,4,3,2);
volatile bool enableTimer = true;
volatile bool resetFlag = false;
unsigned long currentTime = 0; // only touched in loop()
unsigned long lastTick = 0;
void setup() {
lcd.begin(16,2);
pinMode(20, INPUT_PULLUP);
pinMode(21, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(20), startStopTimer, FALLING);
attachInterrupt(digitalPinToInterrupt(21), resetTimer, FALLING);
displayValue(currentTime);
}
void loop() {
static bool wasEnabled = false;
bool enabled = enableTimer;
if (enabled && !wasEnabled) lastTick = millis(); // restart the 1 s count
wasEnabled = enabled;
if (resetFlag) {
resetFlag = false;
currentTime = 0;
lastTick = millis();
lcd.clear();
displayValue(currentTime);
}
if (enabled && millis() - lastTick >= 1000) {
lastTick += 1000;
currentTime++;
displayValue(currentTime);
}
}
void displayValue(unsigned long value) {
lcd.setCursor(0,0);
lcd.print(value);
}
void startStopTimer() {
enableTimer = !enableTimer;
}
void resetTimer() {
resetFlag = true;
}