How to Control Servo Motor in Arduino: Simple Guide
To control a servo motor in Arduino, use the
Servo library to attach the servo to a pin and set its angle with write(). This lets you move the servo arm to any position between 0 and 180 degrees easily.Syntax
The basic syntax to control a servo motor in Arduino involves including the Servo library, creating a Servo object, attaching it to a pin, and then setting the angle.
#include <Servo.h>: Adds the Servo library.Servo servo;: Creates a servo object.servo.attach(pin);: Connects the servo to a digital pin.servo.write(angle);: Moves the servo to the specified angle (0-180).
arduino
#include <Servo.h> Servo servo; void setup() { servo.attach(9); // Attach servo to pin 9 } void loop() { servo.write(90); // Move servo to 90 degrees delay(1000); // Wait 1 second }
Example
This example moves the servo motor from 0 to 180 degrees in steps of 10 degrees, then back to 0. It demonstrates smooth control of the servo angle.
arduino
#include <Servo.h> Servo servo; void setup() { servo.attach(9); // Attach servo to pin 9 } void loop() { for (int angle = 0; angle <= 180; angle += 10) { servo.write(angle); // Move servo to angle delay(500); // Wait half a second } for (int angle = 180; angle >= 0; angle -= 10) { servo.write(angle); // Move servo back delay(500); // Wait half a second } }
Output
Servo motor arm moves smoothly from 0° to 180° and back to 0° in 10° steps with half-second pauses.
Common Pitfalls
Common mistakes when controlling servo motors include:
- Not including the
Servolibrary, causing errors. - Attaching the servo to a pin that does not support PWM (digital pins 2-13 usually work).
- Using
servo.write()with angles outside 0-180 degrees. - Not providing enough power to the servo, which can cause jitter or no movement.
- Calling
servo.attach()repeatedly insideloop()instead ofsetup().
Wrong way:
void loop() {
servo.attach(9); // Wrong: attach inside loop
servo.write(90);
delay(1000);
}Right way:
void setup() {
servo.attach(9); // Attach once in setup
}
void loop() {
servo.write(90);
delay(1000);
}Quick Reference
Here is a quick cheat sheet for controlling a servo motor with Arduino:
| Command | Description |
|---|---|
| #include | Include the Servo library |
| Servo servo; | Create a servo object |
| servo.attach(pin); | Attach servo to a digital pin |
| servo.write(angle); | Set servo position (0-180 degrees) |
| servo.detach(); | Detach servo to stop sending signals |
Key Takeaways
Use the Servo library to easily control servo motors in Arduino.
Attach the servo once in setup() to a PWM-capable pin.
Use servo.write(angle) with angles between 0 and 180 degrees.
Provide stable power to the servo to avoid jitter.
Avoid attaching the servo repeatedly inside the loop.