0

here is a very simple circuit, with a LED between pin 2 and ground, and a loose wire in pin 8.

enter image description here

Here is the sketch that was intended for use with a small 4-contact switch like these in every arduino starter kit :

int yellowCIn = 8;
int yellowCOut = 2;

void setup() {
  pinMode(yellowCIn, INPUT);
  pinMode(yellowCOut, OUTPUT);
}

void loop() {
  if (digitalRead(yellowCIn) == HIGH) {
  digitalWrite(yellowCOut, HIGH);
  }
  else {
    digitalWrite(yellowCOut, LOW);
  }
}

However, simply moving my hand near the loose white wire is enough to light the LED, moving it away to put it off. As I am writing this, with the arduino connected by usb, rather than on the blue battery visible in the picture, I notice moving my hands away from the keyboard lights the led, moving them close to the keyboard powers it off...

So back to my title : are my hands magic, my electronics competency crap (well, it is, for sure) enough that I never heard of such a tremendous static electricity effect (and never fried one of the many computers I built from parts), or does this board have dire problems?

Thanks for your attention :)

pouzzler
  • 159
  • 4

2 Answers2

2

Nothing's broken; you have discovered the nature of a floating pin. Unfortunately, that means that strange things happen...

A very small charge from your hand is triggering the logic because the state of the pin (high or low) is not set. To fix this, you need to add a pull-up or pull-down resistor (or activate the internal input-pullup resistor).

You can read about how to accomplish this here.

legowave440
  • 191
  • 2
  • Sorry for the dunce questions, hopefully I get to the level of not being a dunce soon enough to not get SE to hate me. Thanks :) – pouzzler Apr 01 '16 at 13:54
  • It was NOT a dunce question by the way - it's the difference between building a computer from ready-made parts (motherboards and slot-in cards), and the far more complex business of building those parts yourself. – Andy Apr 01 '16 at 14:16
  • @pouzzler I had the exact same problem when I first started using buttons :D. You're not at all alone; that's what this site is for – legowave440 Apr 01 '16 at 16:13
1

Try configuring your input pin as INPUT_PULLUP instead. This connects an internal pullup resistor to stop the input value from drifting around.

I would only use the "INPUT" mode on its own if I have that pin wired to something on the board and the levels won't be erratic.

Your hands are magic - they pick up interference from various sources and the high impedance input of the chip pick this up...

(There's a bit more on the modes here: Arduino DigitalPins page)

Andy
  • 341
  • 1
  • 6