#include <LiquidCrystal.h>
const uint32_t MICROS_PER_TENTH = 100000UL;
uint32_t microsAtLastTenth = 0UL;
uint16_t days=0;
uint8_t hours=0, minutes=0, seconds=0, tenths=0;
bool countTime = false;
const uint8_t START_PIN = 2;
const uint8_t RESET_PIN = 3;
uint8_t previousState = HIGH;
char buf[20];
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
void setup() {
lcd.begin(16, 2);
pinMode(START_PIN, INPUT_PULLUP);
pinMode(RESET_PIN, INPUT_PULLUP);
}
void loop() {
// deal with start/stop button
uint8_t currentState = digitalRead(START_PIN);
if (currentState != previousState) {
if (currentState == LOW) {
// button just pressed
countTime = !countTime;
}
previousState = currentState;
delay(12); // debounce
}
// deal with reset button
if (digitalRead(RESET_PIN)==LOW) {
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
tenths = 0;
// no need to debounce
}
if ((micros() - microsAtLastTenth) >= MICROS_PER_TENTH) {
// do the actual timekeeping
microsAtLastTenth += MICROS_PER_TENTH;
if (countTime) tenths++;
if (tenths >= 10) {
tenths -= 10;
seconds++;
}
if (seconds >= 60) {
seconds -= 60;
minutes++;
}
if (minutes >= 60) {
minutes -= 60;
hours++;
}
if (hours >= 24) {
hours -= 24;
days++;
}
// format time for display
buf[0] = '0' + (days/10000);
buf[1] = '0' + ((days/1000)%10);
buf[2] = '0' + ((days/100)%10);
buf[3] = '0' + ((days/10)%10);
buf[4] = '0' + (days%10);
buf[5] = 'd';
buf[6] = '0' + (hours/10);
buf[7] = '0' + (hours%10);
buf[8] = ':';
buf[9] = '0' + (minutes/10);
buf[10] = '0' + (minutes%10);
buf[11] = ':';
buf[12] = '0' + (seconds/10);
buf[13] = '0' + (seconds%10);
buf[14] = '.';
buf[15] = '0' + tenths;
buf[16] = 0;
// print the time
lcd.setCursor(0,0);
lcd.print(buf);
}
}