I'm making a simple code for a sawitch. If the switch is pressed the Led connected to pin 4 will lit up and wait for 2 seconds. But as soon as I release the button or switch the LED is getting off. delay is not working.
Any help regarding these will help me a lot. Thanks in advance.
int pushButton = 3;
int LedPin = 4;
int buttonState = 0;
// the setup routine runs once when you press reset:
void setup() {
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
pinMode(LedPin, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
buttonState = digitalRead(pushButton);
if (buttonState == HIGH)
{
digitalWrite(LedPin,LOW);
delay (2000);
}
else
{
digitalWrite(LedPin,HIGH);
delay (2000);
}
}
Yes, it does that indeed. Don't you want that? If you don't, explain into more detail what you really want. As far as I can see you're code does what you tell us you want
ikelectro, you said: "But as soon as I release the button or switch the LED is getting off. delay is not working."
What septillion said is absolutely true. The LED will always be either on or off and the Arduino will always wait two seconds. The delay is working, unless some Major damage has been done to the Arduino base code (which just doesn't happen in real life).
I think it is possible that you just aren't expressing your Problem such that we understand it enough to help you.
To answer your question: "where to put delay in if else statements." Generally speaking, it is never a good idea to do the same Thing at the end of an if and an else. It just inflates the code and makes it use more Flash Memory. Move it to after the if
if (buttonState == HIGH)
digitalWrite(LedPin,LOW);
else
digitalWrite(LedPin,HIGH);
delay (2000);
Does the same Thing. Actually, in this simple case, you don't even Need the variable buttonState. You could simply write digitalWrite(LedPin, !digitalRead(pushButton));
One problem with your code is that it ALWAYS delays for 2 seconds.
If it checks the button and it is HIGH (not pressed) it switches the LED off and then waits for 2 seconds before it even looks at the button again. I don't think you want it to do that. I'd remove the delay(2000) after the digitalWrite(LedPin,LOW); and see if that's nearer to what you want.