1

I just got a simple scheme where i have a button connected to the 5V connector and to the 4th digital PIN and then i got a led connected to the 2nd PIN and to the GND. When i press the button the LED should switch on and when i don't press it, it shouldn't bright. The problem here is that i got a True value when i'm not pressing the button. What could it be? Here goes the code:

int Button=0;

void setup() {
Serial.begin(9600);
pinMode(2, OUTPUT);        
pinMode(4, INPUT);         
}

void loop() {

Button = digitalRead(4);

Serial.println(Button);

if (Button == HIGH) {

  digitalWrite(2, HIGH);

} else {

  digitalWrite(2, LOW);

}

  delay(200);

}
2
  • 1
    Is there a resistor in series with the led ? You may not connect a led to a pin without resistor. When the button is not pressed, the input is not connected to something. It is floating, and when the pin is read, it can be anything. Have you seen the tutorial ? arduino.cc/en/Tutorial/Button
    – Jot
    Oct 13, 2017 at 19:37
  • 1
    or this one arduino.cc/en/Tutorial/InputPullupSerial ?
    – Juraj
    Oct 13, 2017 at 19:43

1 Answer 1

2

You will need a pushbutton connected as follows:

The signal labeled Vout will connect to digital pin 4.

Pushbutton schematic

Explanation:

When the pushbutton is NOT pressed, no current flows through the resistor, and Vout = 0V. When the pushbutton IS pressed, current flows through the resistor, and Vout = 5V.

This resistor is called a pull-down resistor, because it pulls the signal down to ground. A pull-up resistor would reverse the operation of the pushbutton (i.e. Vout = 5V when not pressed, and 0V when pressed.)

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.