Take the 2-minute tour ×
Electrical Engineering Stack Exchange is a question and answer site for electronics and electrical engineering professionals, students, and enthusiasts. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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