1

I am using the pin 4 as an OUTPUT and pin 8 as an INPUT to turn on/off the light, but for some reason it is not working. Light is on all the time, but when I try to input something it gets brighter and doesn't turn off when I don't give anything to pin 8.

LED is connected to pin 4 with a 220 R, and the other side to GND. When pin 8 is connected to 5V pin then the light should come on, and off when I disconnect them.

Here is the code:

void setup() 
{
 Serial.begin(9600);
 pinMode(4, OUTPUT);
 pinMode(8, INPUT);
}
void loop() 
{
 bool on = digitalRead(8);
 if(on)
 {
 digitalWrite(4, HIGH);
 }
 else
 {
 digitalWrite(4, LOW);
 }
}

What am I doing wrong?

Gerben
11.3k3 gold badges22 silver badges34 bronze badges
asked Feb 16, 2016 at 11:26

1 Answer 1

3

Use input with pullup on pin 8 and a button to ground (GND). See below:

const int ledPin = 4;
const int buttonPin = 8;
void setup() 
{
 pinMode(ledPin, OUTPUT);
 pinMode(buttonPin, INPUT_PULLUP);
}
void loop() 
{
 digitalWrite(ledPin, digitalRead(buttonPin));
}

Using the pin as input and disconnecting is not the same as GND. The pin is floating. By using the internal pullup resistor the pin is HIGH when the button is not connected to GND.

answered Feb 16, 2016 at 11:36
2
  • Thank you for your reply. It worked. But I still don't understand why my solution didn't work. Will you be able to explain? Commented Feb 16, 2016 at 12:04
  • 1
    See updated answer. Commented Feb 16, 2016 at 12:19

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.