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?
1 Answer 1
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.
-
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?Dilshod– Dilshod2016年02月16日 12:04:53 +00:00Commented Feb 16, 2016 at 12:04
-
1See updated answer.Mikael Patel– Mikael Patel2016年02月16日 12:19:41 +00:00Commented Feb 16, 2016 at 12:19