Hello all,
Im quite newbie and im stuck with a quite simple problem, please bear with me: i have a button, when is pressed arduino should send a "1" vias serial, orherwise a "0".
Now the problem is that when the button is not pressed and the circuit should be LOW, the serial writes the "zeros" but also the "ones". Here the code:
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int out1;
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, LOW); // turn LED OFF
out1 = 1;
}
else {
digitalWrite(ledPin, HIGH); // turn LED ON
out1 = 0;
}
Serial.println(out1);
delay(100);
}
when i press i get only "1", which is perfect, but when the button is not pressed i get series of "0" and "1", which I dont understand why..
any hint?
thanks,
mat
Do you have a pull up/down resistor? An input that is not being driven by some signal will float, and it sounds like your input is floating.
With a button, frequently the way this is handled is to tie the input pin to +5V through a resistor (e.g. 1k to 10k ohm) so that when the button is not pressed the signal is high. When the button is pressed the input is shorted to ground, causing the input to go low. This inverts your logic (the pin is low when the button is pressed, and vice versa).
You can also use the ATmega's internal pullup resistor by setting the pin state to input, then writing 1 to it. This saves you wiring an external resistor.
ok, now I ve activated the internal pulldown and I have just 2 wires: One from a lead of the button in the inputPin and the other in the ground in.
As result I have the serial.print giving series of 0 and 1 alternately and the LED blinking. When I push the LED is OFF and I have only 0.
Why is it behaving like this? It seems the arduino receives repeately high and low voltage..
When i took off the pin in wire the LED is stays ON ..
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int out1;
int BUTTON;
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
Serial.begin(9600);
pinMode(BUTTON, INPUT);
digitalWrite(BUTTON, HIGH);
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, LOW); // turn LED OFF
out1 = 1;
}
else {
digitalWrite(ledPin, HIGH); // turn LED ON
out1 = 0;
}
Serial.println(out1);
delay(100);
}