//
// blinks several LEDs in different intervals without using the 'delay' function.
// Written in object orientated style.
//
// based on the idea of JIT 06/01/23
// modified to Arduino style "Blink Without Delay" by noiasca
// https://forum.arduino.cc/t/classes-with-arduino/1074105
// code in forum
class LED {
protected:
const uint8_t pin; // the number of the LED pin. Will be handed over on object creation
bool ledState = false; // used to switch on or off the LED
uint16_t interval = 1000; // interval at which to blink (milliseconds)
uint32_t previousMillis = 0; // will store last time LED was updated
public:
LED(uint8_t pin) : pin(pin) {} // you must handover the pin to which you have connected the LED
void begin() { // will initialize hardware based activities
pinMode(pin, OUTPUT);
}
void setInterval(uint16_t interval) { // modify the default time of interval
this->interval = interval; // the parameter is named the same as the member variable, hence we need this-> to access the member variable
}
void blink(unsigned long currentMillis = millis()) { // blinking is based on the Arduino Example "Blink Without Delay"
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
if (ledState == true) {
digitalWrite(pin, LOW); // turn the LED off by making the voltage LOW
} else
{
digitalWrite(pin, HIGH); // turn the LED on (HIGH is the voltage level)}
}
ledState = !ledState;
}
}
};
LED ledA(LED_BUILTIN); // create a LED instance with the built in LED
LED ledB(12);
LED led[] {11, 10}; // create an array of LED objects, hence several pins
void setup() {
ledA.begin(); // will do HW specific activities, e.g. set the pinMode
ledB.begin();
for (auto &i : led) i.begin(); // call begin function for all members of the array led[]
ledB.setInterval(500); // modify the default interval
led[0].setInterval(700);
led[1].setInterval(900);
}
void loop() {
uint32_t currentMillis = millis(); // we will need millis() for several calls, hence read millis() into a variable
ledA.blink(currentMillis);
ledB.blink(); // if you don't handover a timestamp, the function will use millis() internally
for (auto &i : led) i.blink(currentMillis); // call blink function for all members of the array led[]
}