Why can't I get a stable reading from an unpressed switch?

I am trying to figure out how to use/code a switch.

Since I don't have a switch here I just hooked a wire to the pin 2 and a wire to GND. So, to activate my "switch" I just join the two wires.

Then I have the following code:

int MySwitch = 2;

void setup()
{
  Serial.begin(9600);
  pinMode(MySwitch, INPUT);
}

void loop()
{
  Serial.print(digitalRead(MySwitch));
}

When I press my button I get a constant 0 value, and that's OK (I am assuming that 0 is a reliable reading of pressed button). The problem is that when the button is unpressed I get crazy random 0/1 values.

How can I get a stable/constant sign of unpressed button? What am I doing wrong?

Thanks!

That’s normal. Especially when there’s nothing to influence the signal, like an external pullup resistor, or by using…

pinMode(MySwitch, INPUT_PULLUP);

INPUT_PULLUP, not INPUT.

When the wire's unplugged, the input's not conected to anything so stray static electricity can float the voltage value up and down. INPUT_PULLUP internally connects a resistor to the supply voltage so that you have a stable HIGH signal when nothing's on the input.

Cool, thanks to both for so promptly and quickly answer my question! Problem solved!

:)