I started a code to control an Arduino Uno with an LED light. all my electrical is fine, but I'm having trouble with the code as I want to have the LED light run when the button is pressed but turn off after 5 seconds even if it is still pressed down. I've been able to get it to turn off after releasing and waiting 5 seconds by using a delay, but that is not the outcome I want.
I think the issue might be with the int and having it as a global versus local, but I do not know what else to do. I attached the code if yall could help!!!!!
int led = 7;
int BUTTON_PIN = 8;
int buttonState = 0;
int timer;
void setup() {
pinMode(led, OUTPUT);
pinMode (BUTTON_PIN, INPUT);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(BUTTON_PIN);
Serial.println(buttonState);
if (buttonState == HIGH){
while(timer<=5000){
digitalWrite(led,HIGH);
}
}else{
digitalWrite(led,LOW);
int timer=0;
}
}
the limit switch is connected to port the 5v port and the ground port and connected to the led pathway so it can read the voltage and turn on and off based on that.
what do you mean by external pulldown?
it's hard to see what's connected where on the pictures, if you could draw your circuit (just rectangles with used pin names and lines for connectors) and post it here it would be easier
If you use buttonState to start a timer, be it a delay(), a construction with millis() or a hardware timer, each with its own pros and cons, you should be aware that the next time loop() is executed, the buttonState will start the time all over again.
I guess you want to use buttonEdge to start your timer. To detect an edge, you need to remember the previous state and compare it to the present state.
Beyond that, you might think about what you want to happen if the button is released before the timer runs out, or if the button is pushed again before or after the timer has run out.