One of the first things you need to learn when interfacing switches to microcontrollers is the use of pull-up resistors. These ensure that the inputs to the microcontroller settle in either logic high or low when the switch is not made. They are fundamental, so fundamental that Atmel decided to build-in weak pull-up resistors into the ATmega328P used in the Arduino!
Yet a lot of tutorials show external pull-up resistors being used with switches. There’s not really a problem with this – just that it is not required 99% of the time. It might be good to teach the concept, but I regularly see posts on forums where people have connected pull-ups incorrectly, causing them problems. I’ve even seen people confident enough to design a PCB, but have multiple external pull-ups for interfacing to a keypad!
So how do you use the internal pull-ups? It is very simple – when the data direction register is set to input, write a high to the output port:
Or, if you have moved away from the Arduino libraries:
DDRx &= ~(1 << pin);
PORTx |= (1 << pin);
What’s the other 1% where these internal pull-ups won’t do? There are two situations:
- The switch requires a pull-down rather than pull-up – though this can generally be avoided
- You need a strong rather than weak pull-up – sometimes devices draw power from the pull-up, and the 20kOhm internal pull-up is too large.
So, simplify your circuits and remember this feature!