Introduction
Servo motors are widely used in robotics, automation, and DIY projects because they allow precise control over angular movement. In this tutorial, we will learn how to control a basic servo motor using an Arduino. This project will introduce you to the Servo library, one of the most commonly used libraries in Arduino programming.
What You Will Need
- Arduino Uno board
- Servo motor (such as SG90)
- Breadboard (optional)
- Jumper wires
- USB cable for programming
Understanding the Servo Motor
A servo motor has three wires:
- Power (usually red): Connects to 5V
- Ground (usually black or brown): Connects to GND
- Signal (usually yellow or orange): Receives control signals from Arduino
The Arduino sends a PWM (Pulse Width Modulation) signal to the servo motor to set its position.
Setting Up the Hardware
- Connect the servo motor’s power wire to the 5V pin on the Arduino.
- Connect the ground wire to one of the GND pins on the Arduino.
- Connect the signal wire to digital pin 9 on the Arduino.
If you are using a breadboard, you can connect the wires more neatly, but direct wiring will also work for simple projects.
Writing the Code
Open the Arduino IDE and type the following code:
cppCopyEdit#include <Servo.h>
Servo myServo; // Create a servo object
void setup() {
myServo.attach(9); // Attach the servo to pin 9
}
void loop() {
myServo.write(0); // Move servo to 0 degrees
delay(1000); // Wait for 1 second
myServo.write(90); // Move servo to 90 degrees
delay(1000); // Wait for 1 second
myServo.write(180); // Move servo to 180 degrees
delay(1000); // Wait for 1 second
}
How the Code Works
#include <Servo.h>: This imports the Servo library, which contains all the functions needed to control a servo motor.Servo myServo;: Creates an instance of the Servo class to control the motor.myServo.attach(9);: Links the servo object to pin 9.myServo.write(angle);: Commands the servo to move to the specified angle, between 0 and 180 degrees.delay(time);: Waits for the specified time in milliseconds before moving to the next position.
Conclusion
Controlling a servo motor with Arduino is simple and powerful. With just a few lines of code, you can create projects involving movement, such as robotic arms, automatic door openers, and sensor-driven mechanisms. Once you master basic servo control, you can move on to more complex applications like controlling multiple servos simultaneously or using joystick inputs.
