I am using an Arduino Mega to control three LED's with an SPDT center off switch. The common to the switch is 5 volts through a 10K Ohm resistor. The program is designed to light one of the LED's if the switch is set in one position, a different LED if in the opposite position, and a third LED if turned to the off position. The problem is that the LED's "bounce" from one to the other erratically and inconsistently. Placing a hand close to the Arduino increases this activity. Any ideas on what I could do to alleviate this problem? Thanks. Brian
Sounds like the 10k resistor is in the wrong place and you have floating inputs.
It would be better to connect the switch common to GND. Then set up the two input pins on the Arduino with internal pullups, like this:
pinMode(8, INPUT_PULLUP); // Use your pin number
You will need to make some changes to your code: a LOW result from
digitalRead() will now indicate that the switch is closed to that pin, and HIGH that it is open.
Thanks Ray. I'll rewrite the code and see how that goes. Is there a technical answer why a ground signal would not be as susceptible to stray signals as a positive signal? Just curious... Again, thanks for quick response. Brian
From the way I understood your setup, the pullup resistor to +5V was on the switch common, so the the other two switch contacts (connected to the Arduino pins) were neither pulled up nor down, until the switch was moved to close one of them. And even then, the other connection would still be floating. So it was not really an issue of +5V versus GND.
However, there are reasons for using pullups to +5V and switching to GND., rather than the other way round.
The Atmega chips have internal pullup resistors, so no need for physical resistors.
Also, if the switch happened to be a long distance from the Arduino, you would have to run a long +5V connection to the switch. That long connection is (I understand) more prone than a GND connection to picking up electrical noise that could cause problems in other parts of the circuit.