1

I am new into arduino and stuff. So i was playing around with the pull up resistor. It worked fine but the problem rised when I used a delay to turn the led on for few seconds before it gets back to low state it stopped working when I pressed the switch multiple times it may work sometimes but maximum time it is not working

here is the code

const int buttonPin = 4;     
const int ledPin =  12;     
int buttonState = 0;    


void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
        buttonState = digitalRead(buttonPin);
      if (buttonState == LOW) 
  {
    digitalWrite(ledPin, HIGH);
    delay(5000);
  } else 
  {
    digitalWrite(ledPin, LOW);
    delay(5000);
  }
}
  • What does happen, when it doesn't work? Please explain further – chrisl Jun 4 '18 at 20:01
  • the state of the LED doesn't change. – Peouse Dutta Jun 4 '18 at 20:02
  • 3
    you are not reading the switch during the delay(5000).... you have to hold the button down for up to 5 seconds – jsotola Jun 4 '18 at 20:05
  • Change the second delay to lower value, say 100ms. – Gerben Jun 4 '18 at 20:31
  • one of the things that you have to learn when programming is to identify the area of failure .... your program fails to respond to a pushbutton being pressed, it is not LED freezing – jsotola Jun 4 '18 at 22:36
5

Your Arduino does nothing during the delay(5000). So pressing the button during the 5000 mSec that the led is off won't do anything. Or you must be very lucky to press the button in the very small time between one loop and the next.

I learned a lot about timing and delays with this tutorial: Blink Without Delay

| improve this answer | |
  • Actually the Arduino is doing something, just not what the op thinks. – PhillyNJ Jun 5 '18 at 22:50
  • Yes, it's waiting till the delay is over... – ON5MF Jurgen Jun 6 '18 at 5:17
  • it never waits. You should see what delay actually does. – PhillyNJ Jun 6 '18 at 13:23
  • in the case of this code it does wait... otherwise this is what it does: 'Certain things do go on while the delay() function is controlling the Atmega chip however, because the delay function does not disable interrupts. Serial communication that appears at the RX pin is recorded, PWM (analogWrite) values and pin states are maintained, and interrupts will work as they should.' (From the arduino reference) – ON5MF Jurgen Jun 6 '18 at 16:03
  • You should actually see what it does. Then you will know what I’m talking about. – PhillyNJ Jun 6 '18 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.