When you’re building a circuit with an arduino, you might want to add a button to your project. But before you do, you’ll want to understand how a button works.
A button is a switch that can be pressed or released, and it’s often used in conjunction with an LED to control something. Typically, a button is wired to a digital pin on an arduino. When the button is pressed, an input on the arduino will change from LOW to HIGH, which can be used to control an LED or other device.
There are several different ways to wire a button. The most common is to wire the ground side of the switch to the Arduino’s ground rail, and the digital pin side to a pin on the Arduino board.
Another way to connect a button is to wire both the digital pin and the ground side of the switch to the same resistor, then connect the two legs of the resistor to the 5v pin on an arduino. The resistor acts as a pull up on the 5v line to make sure that when you read the pin, it will be HIGH.
The internal resistors on some microcontrollers can also be used to establish a HIGH state. This is a good option because it saves on component count, but there are some drawbacks to this method, as well.
First, a resistor in this position will make the digital pin a “floating” input when the switch isn’t pressed. This can cause the digital input to read erratically. This can be a problem if you have an LED connected to this digital pin.
Alternatively, you can hook up the digital pin to an external resistor to establish a fixed HIGH state. This is less confusing, but isn’t as efficient.
A more complicated button circuit configuration is to connect the ground and data wires of the button to an external pull up resistor, then connect a wire from the digital pin to the Arduino’s 5v pin. You can do this with either an internal or external pull up resistor depending on your project needs.
This will prevent the digital pin from “floating” when the button isn’t pressed, which can cause the digital input to return a random value (HIGH or LOW). The internal pull up resistor will also save space on the board and decrease component count by one.
You can also use an external pull up resistor, but it’s less common than using the internal version. You’ll still need to enable INPUT_PULLUP in your code to do this, though.
Now that we’ve learned how to connect a button to an arduino, let’s build a circuit that turns on the LED when the button is pressed. It’s easy enough to do this by modifying the blink exercise sketch. The program will turn on the LED when you press the button and will turn off the LED when you release it.