Electronic – Using SPST switch as digital input

digital-logicswitches

I am new to "electrical engineering" and I am working on a little arduino project. I want to have a SPST switch be used as a digital input on the board.

I have one of the switch leads connected to posative and the other connected to the digital input. The problem with this is that when the switch it off I can't be sure the input will be grounded. How can I make sure the input is grounded when the switch is off?

Would it work if I connected the digital input to a resistor that is connected to ground so when the switch is off it will be grounded, but when the switch is on it wont short out — would that work?

Best Answer

The most conventional solution would be to connect one side of the switch to ground. Connect the other to the digital input, and also to a resistor between 1 and 10 K ohms going to the positive supply.

Going the other way, with a pull down resistor as Bruno describes, is possible but less preferred. Many inputs already have a degree of implicit pull-up and will read a '1' if unconnected, though not quite reliably. But if your switch is already connected to the positive rail, then a pull down is an okay solution, though many prefer to use a small resistor when connecting logic inputs to the positive rail.

Many microcontrollers also have internal pullup and/or pull down resistors on GPIO pins which can be enabled by writing to a configuration register. If you are driving an input of such a microcontroller you might not need an external pull up/down resistor at all, though not every microcontroller features these.