Build an Arduino Servo Toggle Switch with a Push Button
Build an Arduino Servo Toggle Switch with a Push Button
This project guide will show you how to create a simple yet highly useful circuit: a servo motor that toggles between two positions with each press of a single push button. On the first press, the servo will smoothly sweep from 0 to 180 degrees. On the second press, it will sweep back from 180 to 0 degrees. This is a fundamental concept in robotics and automation, perfect for creating mechanisms like an automatic door latch, a simple robotic arm, a flag waver, or any project that requires a two-state physical action.
We will walk through the required hardware, the wiring, and provide a detailed explanation of the Arduino code that makes it all work.
Hardware and Wiring
The components for this project are minimal and common in most Arduino starter kits. You will need an Arduino board (like an Uno), a standard hobby servo motor (e.g., SG90), a push button, and a few jumper wires.
The wiring is straightforward. The servo's power and ground lines connect to the Arduino's 5V and GND pins, while its signal line connects to a PWM-capable pin (pin 9 in our code). The push button connects between digital pin 2 and GND.
The Arduino Code Explained
The sketch uses the standard Servo.h library, which is included with the Arduino IDE. The code is designed to be clean and easy to understand, using flags to keep track of the servo's state and `for` loops to create a smooth sweeping motion.
Global Variables and Configuration
At the top of the code, we define the pins and the servo's behavior. These are the main values you might want to customize for your project.
#include <Servo.h>
// Define variables for servo and button pins
const int servoPin = 9; // Connect servo signal wire to digital pin 9
const int buttonPin = 2; // Connect push button to digital pin 2
// Define servo movement parameters
const int initialAngle = 0; // Servo's starting angle
const int targetAngle1 = 180; // First target angle
const int targetAngle2 = 0; // Second target angle
const int movingStep = 1; // Step size for smooth movement (1 degree at a time)
Servo myServo; // Create a Servo object
// State-tracking variables
int currentAngle = initialAngle;
bool buttonPressed = false;
bool servoAt180 = false;
servoPin: The pin connected to the servo's signal wire. This must be a PWM pin (marked with a `~` on most Arduino boards).buttonPin: The pin the push button is connected to.initialAngle,targetAngle1,targetAngle2: These define the start and end points of the servo's movement.movingStep: This controls how many degrees the servo moves in each step of the loop. A smaller number creates a smoother, slower motion.
The `setup()` Function
The setup() function runs once when the Arduino is powered on. It initializes the servo, configures the button pin, and sets the servo to its starting position.
void setup() {
myServo.attach(servoPin); // Attaches the servo to its pin
pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as input with internal pull-up
myServo.write(initialAngle); // Move the servo to its initial position
Serial.begin(9600); // Start serial for debugging
}
We use INPUT_PULLUP for the button pin. This activates an internal resistor in the Arduino, which keeps the pin's state HIGH when the button is not pressed. When the button is pressed, it connects the pin to ground, making the state LOW. This useful feature means you don't need to add an external pull-up resistor to your circuit.
The `loop()` - The Core Logic
The main loop continuously checks for a button press. When a press is detected, it moves the servo to its next target position.
void loop() {
// Read the state of the button
int buttonState = digitalRead(buttonPin);
// Check if the button is pressed (LOW) and it wasn't already being held down
if (buttonState == LOW && !buttonPressed) {
delay(50); // Debounce delay to prevent multiple triggers
if (digitalRead(buttonPin) == LOW) { // Re-check the button state
buttonPressed = true; // Mark the button as pressed
if (!servoAt180) {
// If not at 180, move to 180
for (int angle = currentAngle; angle <= targetAngle1; angle += movingStep) {
myServo.write(angle);
delay(15); // Delay between steps to control speed
}
currentAngle = targetAngle1;
servoAt180 = true; // Update state
} else {
// If at 180, move back to 0
for (int angle = currentAngle; angle >= targetAngle2; angle -= movingStep) {
myServo.write(angle);
delay(15);
}
currentAngle = targetAngle2;
servoAt180 = false; // Update state
}
}
}
// Reset the button press flag once the button is released
if (buttonState == HIGH) {
buttonPressed = false;
}
}
The code uses a boolean flag, servoAt180, to remember the servo's last position. When the button is pressed, it checks this flag: if the servo is not at 180 degrees, it moves it there; otherwise, it moves it back to 0. The for loops are what create the smooth sweeping motion, moving the servo one degree at a time with a small delay between each step.
How It Works
Once you upload the code and power on your Arduino, the servo will move to its initial 0-degree position.
- First Press: When you press the button, the code detects the input and begins moving the servo from 0 towards 180 degrees, one degree at a time.
- Second Press: After the servo has reached 180 degrees, the next button press will cause it to sweep back from 180 towards 0 degrees.
This cycle will repeat with each subsequent button press, creating a reliable and predictable toggle mechanism for your project.
Resources & references
No resources yet.
Files📁
No files available.