#include <LiquidCrystal_I2C.h>
#define RED_BUTTON 2
#define GREEN_BUTTON 4
#define DEBOUNCE_PERIOD 10UL
LiquidCrystal_I2C lcd(0x27,16,2);
unsigned long startTime = 0;
unsigned long elapsedTime = 0;
bool isRunning = false;
bool isGreenButtonPressed()
{
static int debounced_button_state = HIGH;
static int previous_reading = HIGH;
static unsigned long last_change_time = 0UL;
bool isPressed = false;
int current_reading = digitalRead(GREEN_BUTTON);
if (previous_reading != current_reading)
{
last_change_time = millis();
}
if (millis() - last_change_time > DEBOUNCE_PERIOD)
{
if (current_reading != debounced_button_state)
{
if (debounced_button_state == HIGH && current_reading == LOW)
{
isPressed = true;
}
debounced_button_state = current_reading;
}
}
previous_reading = current_reading;
return isPressed;
}
bool isRedButtonPressed()
{
static int debounced_button_state = HIGH;
static int previous_reading = HIGH;
static unsigned long last_change_time = 0UL;
bool isPressed = false;
int current_reading = digitalRead(RED_BUTTON);
if (previous_reading != current_reading)
{
last_change_time = millis();
}
if (millis() - last_change_time > DEBOUNCE_PERIOD)
{
if (current_reading != debounced_button_state)
{
if (debounced_button_state == HIGH && current_reading == LOW)
{
isPressed = true;
}
debounced_button_state = current_reading;
}
}
previous_reading = current_reading;
return isPressed;
}
void updateLCD(unsigned long seconds);
void setup(){
pinMode(RED_BUTTON, INPUT_PULLUP);
pinMode(GREEN_BUTTON, INPUT_PULLUP);
lcd.init();
lcd.clear();
lcd.backlight();
}
void loop(){
if(isGreenButtonPressed()) {
if(isRunning) {
elapsedTime += (millis() - startTime) / 1000;
isRunning = false;
} else {
startTime = millis();
isRunning = true;
}
}
if(isRedButtonPressed()) {
if(isRunning) {
elapsedTime += (millis() - startTime) / 1000;
isRunning = false;
}
elapsedTime = 0;
}
if(isRunning) {
updateLCD(elapsedTime + (millis() - startTime) / 1000);
} else {
updateLCD(elapsedTime);
}
delay(1000);
}
void updateLCD(unsigned long seconds) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Elapsed Time:");
lcd.setCursor(0, 1);
lcd.print(seconds);
}