# How to fight static charge/constant electromagnetic on Arduino (attachInterrupt)

I have short wires with button attached to pin 2 and ground. However, even without touching anything, the led is toggled many times a minute. Due to that (I guess) it is reacting to my button press very very randomly. It looks like the constant charge on the wires are interfering the actual button press and acting like antenna. I've tried different Arduino UNO boards, same results, so the board is not faulty.

int pin = 9;
volatile boolean state = LOW;

void setup()
{
pinMode(pin, OUTPUT);
}

void loop()
{
digitalWrite(pin, state);

delay(1000);// for debug purposes
}

{
if (state ==LOW)
{
state=HIGH;
}
else
{
state=LOW;
}

}


Will appreciate if anyone can recommend hardware solution to this.

-

The problem occurs due to Arduino's inputs being in high impedance state by default. In effect, they are capacitive sensors.

You need to enable pull-up on the pin you are using as input:

pinMode(2, INPUT);
digitalWrite(2, HIGH); // Enable internal 20 kOhm pull-up resistor for this pin

If this is not done, although the pins do default to inputs, they float, as you have discovered.

No other changes need to be made, and certainly no hardware changes are needed.

-
This certainly addressed most of the issue. I also added RC filter (100nF, 10K) which fully solved it! thanks!!! – Pablo Nov 3 '12 at 11:39
I assume the RC was needed to debounce the switch, not for random switching when the switch is untouched? An alternative is to do the debounce in Arduino code, though that's a separate question. – Anindo Ghosh Nov 3 '12 at 12:17
Right, debouncing was the second problem after random switching. – Pablo Nov 3 '12 at 12:19