Hi! I am working on a project where I would like an LED to light up for 5 seconds from the moment a button is pushed, regardless of how long the button is held down. I'm running into trouble with how to do this, because the digitalRead(buttonPin) will be HIGH for an extended amount of time. I've made a button state change detection that I feel like should work, but it's not.
int ledPin = 12;
int buttonPin = 13;
int buttonState = 0;
int prevButtonState = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(ledPin, LOW);
}
void loop()
{
buttonState = digitalRead(buttonPin);
if ((buttonState != prevButtonState) && (buttonState = HIGH)){
prevButtonState = buttonState;
digitalWrite(ledPin, HIGH);
delay(5000);
digitalWrite(ledPin, LOW);
}
prevButtonState = 0;
}
Even though I think the if statement should run once when the button state changes, it seems to be ongoing until the button is released. As of now, the button remains on the entire time it's pressed, and when released, waits 5 seconds to turn off.
Any ideas as to why this is not working? Any help is much appreciated.