Strange Arduino Behavior with jumpers

i'm using an arduino uno and i want to simulate a button. I dont have a button so i "built" one by connecting a wire to Digital3 and one to GND and pressing them together. To notice a HIGH at Digital3 i connected a LED to Digital5.

When i press the GND wire to the Digital3 wire, it works. The clue is that if i touch the digital3 wire with my finger (without pressing both wires together), the LED lights! The wire is a standart isolated wire for breadboards...

My code:

 void setup(){
  pinMode(3, INPUT);
  pinMode(5, OUTPUT);
}

void loop(){
  if(digitalRead(3) == HIGH){
     digitalWrite(5, HIGH);
     delay(500);
     digitalWrite(5, LOW); 
  }
}

Can somebody explain me why this happens?


That's just because the pin 3 is set in High impedance mode. This way even the small antenna made by the wire and your finger (which intercept a lot of electric noise) can trigger the pin and so show a high (or low) value.

In your case the LED lights when you DON'T press the wires together, right? Anyway if you have a "floating" input, like this one, I suggest you to set the port in pullup mode; this way you always have a known state (instead of an unknown one, like in this case). To do so just change

pinMode(3, INPUT);

with

pinMode(3, INPUT_PULLUP);

Repeat the experiment and... it will not float anymore...

链接地址: http://www.djcxy.com/p/78600.html

上一篇: Arduino液晶屏奇怪的行为

下一篇: 奇怪的Arduino行为与跳线