Reputation: 123
I used the following code to digital read the pin input and see if it is high or low.
The problem is the Arduino is giving the wrong values. It gives some times 0 or some time high even though the pin in always low.
It also gives low or 0 as answer though the pin is high is there any one able to help me with this?
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
delay(1000);
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(1000); // delay in between reads for stability
}
Upvotes: 0
Views: 2210
Reputation: 11389
You have to use a pull-down(3) or pull-up(4) resistor:
Use the internal pull-up resistor like this:
pinMode(pin, INPUT); // set pin to input
digitalWrite(pin, HIGH); // activate internal pull-up resistor
that should do it also.
Upvotes: 1