Skip to content

Instantly share code, notes, and snippets.

@dropmeaword
Created March 6, 2018 18:19
Show Gist options
  • Save dropmeaword/72a9f0064f1683523dc40facdf1f7a7d to your computer and use it in GitHub Desktop.
Save dropmeaword/72a9f0064f1683523dc40facdf1f7a7d to your computer and use it in GitHub Desktop.
LED flasher for Arduino without delays
class Flasher
{
int ledPin; // the number of the LED pin
long OnTime; // milliseconds of on-time
long OffTime; // milliseconds of off-time
// These maintain the current state
int ledState; // ledState used to set the LED
unsigned long previousMillis; // will store last time LED was updated
bool flashing;
unsigned long flashingStarted;
unsigned long flashingTime;
public:
Flasher(int pin, long on, long off)
{
ledPin = pin;
pinMode(ledPin, OUTPUT);
OnTime = on;
OffTime = off;
ledState = LOW;
previousMillis = 0;
}
void flash(int howlong = 1000) {
flashing = true;
flashingStarted = millis();
flashingTime = howlong;
}
void stop() {
flashing = false;
}
void update()
{
// check to see if it's time to change the state of the LED
unsigned long currentMillis = millis();
if(flashing && (currentMillis - flashingStarted) >= flashingTime ) {
stop();
}
if(flashing) {
if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
{
ledState = LOW; // Turn it off
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
{
ledState = HIGH; // turn it on
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
}
} // update ()
}; // class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment