Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
millis demo for turning something on or off after some time
// Software timer with millis()
// Turn on the system led for 4 seconds,
// when a switch (connected to pin 2 and GND) is pressed.
// The 4 seconds starts when the switch is released.
//
// When the timing should start at the moment the
// switch is pressed, then the State Change Detection
// should be added.
//
// Created and tested at Tinkercad.com
const int switchPin = 2;
unsigned long previousMillis;
const unsigned long interval = 4000;
bool enabled = false;
void setup()
{
pinMode( switchPin, INPUT_PULLUP);
pinMode( LED_BUILTIN, OUTPUT);
}
void loop()
{
if( digitalRead( switchPin) == LOW) // low is active
{
digitalWrite( LED_BUILTIN, HIGH); // turn on led
previousMillis = millis();
enabled = true; // turn on software timer
}
if( enabled) // software timer is active ?
{
if( millis() - previousMillis >= interval)
{
digitalWrite( LED_BUILTIN, LOW); // turn off led
enabled = false; // stop software timer
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment