class Timer {
private:
unsigned long nextChangeTime;
unsigned long timeOn_;
boolean overFlow;
public:
void TimerSet (unsigned long timeOn) {
timeOn_ = timeOn;
unsigned long currentTime = micros();
nextChangeTime = currentTime + timeOn;
if (nextChangeTime > currentTime) {
overFlow = false;
} else {
overFlow = true;
}
}
boolean TimerActive() {
unsigned long currentTime = micros();
boolean val = false;
if (! overFlow) {
if (currentTime < nextChangeTime) {
val = true;
}
} else if ((currentTime + timeOn_)<(nextChangeTime + timeOn_)){
val = true;
}
return val;
}
};
int LED1 = 7;
int LED2 = 8;
int LED3 = 9;
unsigned long delay1 = 1000000;
unsigned long delay2 = 500000;
unsigned long delay3 = 250000;
int BTN = 4;
unsigned long debounceDuration = 50; // millis
unsigned long lastTimeButtonStateChanged = 0;
byte previousButtonState = LOW;
byte state = 0; // 0: LEDs off, 1: LEDs on, 2: LED1, 3: LED2, 4: LED3
Timer TMR1;
Timer TMR2;
Timer TMR3;
void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(BTN, INPUT_PULLUP);
}
void loop() {
// Button debounce
unsigned long currentMillis = millis();
if (millis() - lastTimeButtonStateChanged > debounceDuration) {
byte buttonState = digitalRead(BTN);
// Check for button press
if (buttonState != previousButtonState) {
lastTimeButtonStateChanged = millis();
previousButtonState = buttonState;
if (buttonState == LOW) {
// Cycle through LED states (0-4)
if (state <= 3) {
state ++;
} else {
state = 0;
}
}
}
}
switch (state) {
case 0:
// Turn off all LEDs
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
break;
case 1:
// Turn on all LEDs
ledBlink(LED1, TMR1, delay1);
ledBlink(LED2, TMR2, delay2);
ledBlink(LED3, TMR3, delay3);
break;
case 2:
// Turn on LED1
ledBlink(LED1, TMR1, delay1);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
break;
case 3:
// Turn on LED2
ledBlink(LED2, TMR2, delay2);
digitalWrite(LED1, LOW);
digitalWrite(LED3, LOW);
break;
case 4:
// Turn on LED3
ledBlink(LED3, TMR3, delay3);
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
break;
}
}
void ledBlink(int LED, Timer& TMR, unsigned long delay){
if (!TMR.TimerActive()) {
digitalWrite(LED, !digitalRead(LED));
TMR.TimerSet(delay);
}
}