// Source :: Lab 6
// Description :: Lab 6 - Digital Count Down Timer
// Programmed by :: Douglas Vieira Ferreira / 03-23-2024
/*
The assignment applies to construct a simple Count Down Timer using the LCD screen
counting from 02 min 59 seconds down to ZERO
*/
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
const int buttonPin = 2; // Push button pin
const int potPin = A0; // Potentiometer pin
unsigned long previousMillis = 0;
const long interval = 1000; // one second
bool timerRunning = false;
bool paused = false;
int setSeconds = 0;
int countdownSeconds;
int lastDisplayedTime = -1; // To track the last displayed time for update checks
String lastDisplayedLabel = ""; // To track the last displayed label for update checks
void setup() {
lcd.begin(16, 2);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
int potValue = analogRead(potPin);
int currentSetSeconds = map(potValue, 0, 1023, 0, 300); // Map 0-1023 to 0-300 seconds
if (!timerRunning) {
setSeconds = currentSetSeconds;
}
int buttonState = digitalRead(buttonPin);
static int lastButtonState = buttonState;
// Button press with debounce
if (buttonState == HIGH && lastButtonState == LOW && millis() - previousMillis > 200) {
previousMillis = millis(); // reset the debounce timer
if (!timerRunning) {
countdownSeconds = setSeconds;
timerRunning = true;
paused = false;
} else {
paused = !paused;
}
}
lastButtonState = buttonState;
if (timerRunning && !paused) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (countdownSeconds > 0) {
countdownSeconds--;
} else {
timerRunning = false;
paused = false;
}
}
}
if (timerRunning) {
if (lastDisplayedTime != countdownSeconds || lastDisplayedLabel != "RUNNING") {
displayTime("Lab06-RUNNING", countdownSeconds);
lastDisplayedTime = countdownSeconds;
lastDisplayedLabel = "RUNNING";
}
} else {
if (lastDisplayedTime != setSeconds || lastDisplayedLabel != "SET") {
displayTime("Lab06-Set Value", setSeconds);
lastDisplayedTime = setSeconds;
lastDisplayedLabel = "SET";
}
}
}
void displayTime(String label, int time) {
int minutes = time / 60;
int seconds = time % 60;
lcd.setCursor(0, 0);
lcd.print(label);
lcd.setCursor(0, 1);
lcd.print((minutes < 10) ? "0" : "");
lcd.print(minutes);
lcd.print(":");
lcd.print((seconds < 10) ? "0" : "");
lcd.print(seconds);
}