The end goal of this program is to push a button and have a relay that is connected to an output turn on a light. I'm very new to programming. I want to push a NO button and have the output stay high for 1 hour then go low. I'm not sure if i have taken the correct approach for this program or not. all feedback is welcome. One issue im having is that i don't know how to keep the output high after releasing the button. i cannot use a one hour delay so im thinking i should count the amount of 1 second delays (3600 times) but that doesn't stop the output from becoming low.
int LED = 10;
int BUTTON = 2;
void setup() {
pinMode(LED,OUTPUT);
pinMode(BUTTON,INPUT);
}
void loop() {
if(digitalRead(BUTTON) == HIGH)
{delay(1000 );
digitalWrite(LED,HIGH);
}
}
Hi Brenden. Welcome to the forum! First things first, post you code using code blocks and use the auto format function in the IDE to format it for readability. Here is your code properly posted:
int LED = 10;
int BUTTON = 2;
void setup()
{
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT);
}
void loop()
{
if (digitalRead(BUTTON) == HIGH)
{
delay(1000);
digitalWrite(LED, HIGH);
}
}
You didn't write your output pin LOW to start with.
Use the built-in pullup resistor on the input pin, and test LOW for a closed switch, wired between pin and ground.
How is your LED wired?
i cannot use a one hour delay
Why not ?
Here is your program posted in the recommended fashion having been Auto Formatted in the IDE and posted using code tags
int LED = 10;
int BUTTON = 2;
void setup()
{
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT);
}
void loop()
{
if (digitalRead(BUTTON) == HIGH)
{
delay(1000 );
digitalWrite(LED, HIGH);
}
}
Start by putting the delay() after the digitalWrite() and read up on pulldown resistors to keep the input in a known state at all times. Better still, read up on INPUT_PULLUP as a parameter to pinMode() to eliminate the need for eternal resistors
Regarding the logic question, you can set a flag indicating that the output is high. While the flag is set you would check the millis() clock to see of 3,600,000 milliseconds have passed. That way you don't have to use a delay. If you like you could also check the button again and cancel the output if it is pressed again.