Connecting a Push Button to an Arduino Uno with Two Wires
This isn't as complicated as some tutorials make it seem. You don't need a resistor and each push button just needs one wire to an input pin and one wire to ground. Wire up your button to your Uno like this:
In the setup()
function of your code set the input pin to INPUT_PULLUP
:
void setup() {
pinMode(8, INPUT_PULLUP);
}
To determine if your button is being pushed you do a standard digitalRead
on the pin. The only tricky part with this is that you aren't looking for a HIGH
signal like you might assume – your button will give off LOW
when it's pressed. You'll also want to add a delay
statement to limit the amount of reads per second you perform on the button. This keeps your code from executing over and over when your button is held down. Here's the code:
void loop() {
if (digitalRead(8) == LOW) {
//The button is pressed!
}
delay(100);
}
Multiple Buttons
It's easy to expand out to more buttons – just make sure they share a common ground. Here's an example with two buttons:
void setup() {
pinMode(12, INPUT_PULLUP);
pinMode(11, INPUT_PULLUP);
}
void loop() {
if (digitalRead(12) == LOW) {
//Button one is pressed!
}
if (digitalRead(11) == LOW) {
//Button two is pressed!
}
delay(100);
}
Bonus Pins
If you're out of digital pins on your Uno, the analog input pins can be used as bonus digital pins – great if you've already used all your digital pins up through something with a lot of wiring like a seven-segment display.