1
\$\begingroup\$

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()
{
  attachInterrupt(0, blink, CHANGE);
  pinMode(pin, OUTPUT);
}

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

  delay(1000);// for debug purposes
}

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

}

Will appreciate if anyone can recommend hardware solution to this.

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ This certainly addressed most of the issue. I also added RC filter (100nF, 10K) which fully solved it! thanks!!! \$\endgroup\$
    – Pablo
    Nov 3, 2012 at 11:39
  • \$\begingroup\$ 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. \$\endgroup\$ Nov 3, 2012 at 12:17
  • \$\begingroup\$ Right, debouncing was the second problem after random switching. \$\endgroup\$
    – Pablo
    Nov 3, 2012 at 12:19
  • \$\begingroup\$ Any reason not to use pinMode(2, INPUT_PULLUP);? \$\endgroup\$
    – arve0
    Sep 7, 2016 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.