Hi, I need assistance in programming at timed switch.
When I close a switch, I need an LED to light up for 50ms, then turn off (even though the switch is still closed). When I open the switch and close it again, this needs to repeat.
What I am doing is more complicated than this, but the concept is the same.
const byte pinLED = LED_BUILTIN; //define LED pin
const byte pinSwitch = 2; //switch input (pressed == LOW)
unsigned long
timeLED;
byte
lastSwitch; //keep track of what the switch "was' so we can detect a change
#define OFF false //makes code a little easier to read
#define ON true
bool
bstateLED; //internal tracker of LED state (on or off)
void setup()
{
//set up the switch pin as input pullup
pinMode( pinSwitch, INPUT_PULLUP );
lastSwitch = digitalRead( pinSwitch ); //read the state of the switch to establish a value for the first loop() check
//setup the LED
pinMode( pinLED, OUTPUT );
digitalWrite( pinLED, LOW );
bstateLED = OFF;
}//setup
void loop()
{
byte
currSw;
//read the switch...
currSw = digitalRead( pinSwitch );
//...if it's not the same as the last read...
if( currSw != lastSwitch )
{
//make the curr the last
lastSwitch = currSw;
//if the curr is low the button was pressed (high-to-low transition)
//if the LED is off right now, turn it on and start timing a 50mS period
//if the LED is already on, just ignore this press
if( currSw == LOW && bstateLED == OFF )
{
digitalWrite( pinLED, HIGH );
bstateLED = ON;
timeLED = millis();
}//if
}//if
//if the LED is on now, see if it's time to turn it off
if( bstateLED == ON )
{
//time elapsted >= 50mS?
if( (millis() - timeLED) >= 50 )
{
//yes; turn off the LED and set the internal flag to 'off'
digitalWrite( pinLED, LOW );
bstateLED = OFF;
}//if
}//if
}//loop
That example shows you very specifically how to detect when a switch BECOMES closed. From that you can figure out how to detect when it BECOMES open. That information will tell you when it's time to turn on the LED.
That example shows you very specifically how to detect when a switch BECOMES closed. From that you can figure out how to detect when it BECOMES open. That information will tell you when it's time to turn on the LED.