/*
Adaptation of code from J-M-L:
*/
class FlashingLed {
private:
byte ledPin;
byte flashCount;
byte preset;
unsigned long onTime, offTime, lastMillis;
public:
FlashingLed(const byte pin, const byte count,const unsigned long on, const unsigned long off) : ledPin(pin), flashCount(count),onTime(on), offTime(off) {}
void begin() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // Turn LED on
lastMillis = millis(); // remember when we did so
}
void flashWhenNeeded(bool enabled) {
if (enabled) {
if (digitalRead(ledPin) == HIGH) { // if the led is ON a it's the right time, turn it off (HIGH is on)
if (millis() - lastMillis >= onTime) { // check on time and turn LED off if time has expired
lastMillis += onTime; // Add the value of onTime to lastMillis ready to start the next timing interval
digitalWrite(ledPin, LOW);
flashCount--; // Turn LED off
}
} else { // LED is off, if it's the right time, turn it on
if (millis() - lastMillis >= offTime) { // check off time and turn LED on if time has expired
lastMillis += offTime; // Add the value of offTime to lastMillis ready to start the next timing interval
digitalWrite(ledPin, HIGH); // Turn LED on
}
}
}
else digitalWrite(ledPin, LOW);
}
void flashNTimes(bool enabled){
if(enabled){
flashWhenNeeded(true);
if(flashCount==0){
flashWhenNeeded(false);
}
}
else flashCount=preset;
}
};
const byte pb1 = A0; //
const byte pb2 = A1; // must precede instantiation of leds
FlashingLed ledGrn{2, 3,500, 500}; // pin 2, 500ms ON and 500 ms OFF
FlashingLed ledRed {3, 5,1750, 350}; // pin 3, 1750ms ON and 350ms OFF
void setup() {
Serial.begin(115200);
Serial.println(F(__FILE__));
pinMode(pb1, INPUT_PULLUP);
pinMode(pb2, INPUT_PULLUP);
ledGrn.begin();
ledRed.begin();
Serial.println("Setup complete");
}
void loop() {
//ledGrn.flashWhenNeeded(digitalRead(pb2) ? false : true);
ledGrn.flashNTimes(digitalRead(pb2) ? false : true);
ledRed.flashNTimes(digitalRead(pb1) ? false : true);
// ledRed.flashWhenNeeded(digitalRead(pb1) ? false : true);
}