Tutorial 11 – Using Buttons with Arduino
Welcome back to the CraftedTech Engineering Arduino tutorial series! In this tutorial, we’ll explore how to use buttons with Arduino. Buttons are an essential component of interactive projects. By reading the state of a button, you can make your Arduino respond to user input.
🔌 What You’ll Need
- 1 Arduino Board (e.g., Arduino UNO)
- 1 Pushbutton
- 1 10kΩ Resistor
- Breadboard
- Jumper wires
- USB cable for Arduino
You can order the required components here:
🧠 What Is a Pushbutton?
A pushbutton is a simple mechanical switch that makes or breaks a connection when pressed. It’s a great way to interact with your Arduino. By detecting when the button is pressed, you can trigger actions like turning on an LED, starting a motor, or activating a relay.
In this tutorial, we’ll use a pushbutton to turn an LED on or off.
🧾 Step-by-Step Instructions
🔧 Step 1: Wiring the Button
- Connect one end of the pushbutton to digital pin 2 on the Arduino.
- Connect the other end to GND.
- Place a 10kΩ resistor between digital pin 2 and 5V to pull the button high when it’s not pressed.
💻 Step 2: Arduino Code to Detect Button Press
int buttonPin = 2; // Pin for the pushbutton
int ledPin = 13; // Pin for the LED
int buttonState = 0; // Variable to store the button state
void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(buttonPin, INPUT); // Set button pin as input
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the button state
if (buttonState == HIGH) { // If the button is pressed
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
}
🔍 Code Breakdown
- pinMode(): Sets up the input/output mode for the pins.
- digitalRead(): Reads the state of the button (HIGH or LOW).
- digitalWrite(): Controls the LED based on the button press.
🧪 Try This!
- Add another button to control a different LED or perform a different action.
- Modify the code to toggle the LED each time the button is pressed.
🛠️ Troubleshooting Tips
- Ensure you’ve connected the button properly and that the resistor is in place.
- If the LED stays on or off, check the button wiring and make sure the button isn’t stuck.
- Use Serial Monitor to debug and check if the button state is being read correctly.
🧭 What You Learned in This Tutorial
✔️ How to wire a pushbutton to Arduino
✔️ How to use digitalRead() to read button states
✔️ How to turn an LED on or off based on button input
✔️ How to troubleshoot button wiring issues
📌 Next Up: Tutorial 12 – Using a Servo Motor with Arduino
In the next tutorial, we’ll teach you how to control a servo motor with Arduino. Servo motors are great for projects that require precise position control, such as robotic arms or camera pans!
📣 Don’t forget to follow CraftedTech Engineering for more hands-on tutorials and project ideas!
🔗 Website: craftedtechengineering.com
📘 Facebook: @CraftedTechEngineering
📺 YouTube: @CraftedTechEngineering