#include <Arduino.h>
#include <LiquidCrystal.h>
#define TOGGLE_LED_PIN 5
#define INCREMENT_PIN 6
#define DECREMENT_PIN 7
#define MAIN_LED_PIN 8
#define AUX_LED_PIN 9
LiquidCrystal lcdDisplay(A0, A1, A2, A3, A4, A5);
bool isLedOn = false;
int blinkDuration = 1000;
unsigned long systemStartTime; // Variable to store the system start time
const int MIN_BLINK_DURATION = 100;
const int MAX_BLINK_DURATION = 2000;
const int LCD_COLUMNS = 16;
const int LCD_ROWS = 2;
void setup() {
pinMode(TOGGLE_LED_PIN, INPUT);
pinMode(INCREMENT_PIN, INPUT);
pinMode(DECREMENT_PIN, INPUT);
pinMode(MAIN_LED_PIN, OUTPUT);
pinMode(AUX_LED_PIN, OUTPUT);
Serial.begin(9600);
lcdDisplay.begin(LCD_COLUMNS, LCD_ROWS);
// Configure Timer1 for auxiliary LED blinking
TCCR1A = 0;
TCCR1B = 0;
TCCR1B |= (1 << CS11) | (1 << CS10); // 64 prescaler
TCNT1 = 40535; // Reload value for timer
TIMSK1 |= (1 << TOIE1); // Enable timer overflow interrupt
systemStartTime = millis(); // Record system start time
}
ISR(TIMER1_OVF_vect) {
TCNT1 = 40535; // Reload timer value
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // Toggle AUX LED
}
void loop() {
handleButtonAndLed();
taskBlinkAuxLed();
taskChangeBlinkDuration();
displaySystemUptime(); // New task to display system uptime
}
void refreshLcd() {
lcdDisplay.clear();
lcdDisplay.print("LED is ");
lcdDisplay.print(isLedOn ? "On " : "Off");
lcdDisplay.setCursor(0, 1);
lcdDisplay.print("Blink:");
lcdDisplay.print(blinkDuration);
lcdDisplay.print("ms");
}
void handleButtonAndLed() {
static bool previousButtonState = LOW;
bool currentButtonState = digitalRead(TOGGLE_LED_PIN);
if (currentButtonState != previousButtonState && currentButtonState == HIGH) {
isLedOn = !isLedOn;
analogWrite(MAIN_LED_PIN, isLedOn ? 255 : 0);
refreshLcd();
}
previousButtonState = currentButtonState;
}
void taskBlinkAuxLed() {
static unsigned long lastMillis = 0;
if (!isLedOn && (millis() - lastMillis >= blinkDuration)) {
lastMillis = millis();
digitalWrite(AUX_LED_PIN, !digitalRead(AUX_LED_PIN));
} else if (isLedOn) {
digitalWrite(AUX_LED_PIN, LOW);
}
}
void taskChangeBlinkDuration() {
if (digitalRead(INCREMENT_PIN) == HIGH) {
blinkDuration = max(MIN_BLINK_DURATION, blinkDuration - 100);
refreshLcd();
delay(200);
} else if (digitalRead(DECREMENT_PIN) == HIGH) {
blinkDuration = min(MAX_BLINK_DURATION, blinkDuration + 100);
refreshLcd();
delay(200);
}
}
void displaySystemUptime() {
static unsigned long lastDisplayTime = 0;
unsigned long currentTime = millis();
// Update the display every 5 seconds
if (currentTime - lastDisplayTime >= 5000) {
unsigned long uptime = currentTime - systemStartTime; // Calculate system uptime
lcdDisplay.setCursor(0, 0);
lcdDisplay.print("Uptime: ");
lcdDisplay.print(uptime / 1000); // Convert milliseconds to seconds
lcdDisplay.print("s");
lastDisplayTime = currentTime; // Update the last display time
}
}