1

enter image description hereHello guys, this is my code and I am basically doing if-else statement.

int led = D2; 
int but = D1; 
void setup() {
 pinMode(led, OUTPUT); 
 pinMode(but, INPUT); 
}
void loop() {
 if (digitalRead(but) == HIGH){
 digitalWrite(led, HIGH);
 }else{
 digitalWrite(led, LOW);
 }
}

I have also attached the photo so that you can diagnose the situation.

The led show only glow if the button is pressed. But the led keeps glowing for longer time and I don't know why. I think there is current leak somewhere in the circuit or the internal processing is slow. Please help me guys.enter image description here

Juraj
18.3k4 gold badges31 silver badges49 bronze badges
asked Sep 14, 2018 at 12:11
1
  • The circuit seems like it's wrong. When a button is pressed it wil fluctuate some before it going to be stable. Try this: " bool state=digitalRead(but) digitalWrite(led, state); " also similar problem: arduino.stackexchange.com/questions/3425/… Commented Sep 14, 2018 at 13:21

1 Answer 1

2

Your button and pull-up configuration is not correct, so when the button is not being pressed, the pin D1 is floating, being pulled neither HIGH nor LOW.

Instead, use a pull-up resistor as shown. When the button is not pressed, D1 is connected to GND through a resistor. When the button is pressed, the 3.3V source has a direct path to D1.

schematic

simulate this circuit – Schematic created using CircuitLab

answered Sep 14, 2018 at 13:11
2
  • why pull-down? it is simpler to use the internal pullup Commented Sep 14, 2018 at 16:55
  • Because the asker has coded for a pull-up. Yes, it’s trivial to change. Commented Sep 14, 2018 at 17:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.