class LEDBlinker {
public: LEDBlinker(int ledpin, int onInterval, int offInterval) {
pin = ledpin;
state = LOW;
previousTime = 0;
onInt = onInterval;
offInt = offInterval;
blinking = true;
pinMode(pin, OUTPUT);
}
void update() {
if (!blinking) return;
unsigned long currentTime = millis();
if ((state == HIGH) && (currentTime - previousTime >= onInt)) {
previousTime = currentTime;
state = LOW;
digitalWrite(pin, state);
} else if ((state == LOW) && (currentTime - previousTime >= offInt)) {
previousTime = currentTime;
state = HIGH;
digitalWrite(pin, state);
}
}
void stopBlink() {
blinking = false;
digitalWrite(pin, LOW);
}
void startBlink() {
blinking = true;
previousTime = millis();
}
bool isBlinking() {
return blinking;
}
private: int pin;
int onInt;
int offInt;
int state;
unsigned long previousTime;
bool blinking;
};
const int LED_PINS[5] = {12, 11, 10, 9, 8};
LEDBlinker leds[5] = {
LEDBlinker(12, 500, 500),
LEDBlinker(11, 1000, 500),
LEDBlinker(10, 200, 200),
LEDBlinker(9, 700, 300),
LEDBlinker(8, 300, 300)
};
void setup() {
Serial.begin(9600);
}
void loop() {
for (int i = 0; i < 5; i++) {
leds[i].update();
}
if (Serial.available()) {
char ch = Serial.read();
if (ch == ' ') {
bool anyBlinking = false;
for (int i = 0; i < 5; i++) {
if (leds[i].isBlinking()) {
anyBlinking = true; break;
}
}
if (anyBlinking) {
for (int i = 0; i < 5; i++) {
leds[i].stopBlink();
} Serial.println("All LEDs stopped blinking.");
} else {
for (int i = 0; i < 5; i++) {
leds[i].startBlink();
}
Serial.println("All LEDs started blinking.");
}
} else if (ch >= '1' && ch <= '5') {
int ledIndex = ch - '1';
if (leds[ledIndex].isBlinking()) {
leds[ledIndex].stopBlink();
Serial.print("LED ");
Serial.print(ledIndex + 1);
Serial.println(" stopped blinking.");
} else {
leds[ledIndex].startBlink();
Serial.print("LED ");
Serial.print(ledIndex + 1);
Serial.println(" started blinking.");
}
}
}
}