How to Use Servo Library in Arduino: Simple Guide
To use the
Servo library in Arduino, first include it with #include <Servo.h>, then create a Servo object. Attach the servo to a pin using attach() and control its angle with write().Syntax
The basic syntax to use the Servo library involves including the library, creating a Servo object, attaching it to a pin, and setting the servo angle.
#include <Servo.h>: Adds the Servo library to your sketch.Servo servoName;: Creates a servo object to control one servo.servoName.attach(pin);: Connects the servo object to a specific Arduino pin.servoName.write(angle);: Moves the servo to the specified angle (0 to 180 degrees).
arduino
#include <Servo.h> Servo myServo; // Create servo object void setup() { myServo.attach(9); // Attach servo to pin 9 } void loop() { myServo.write(90); // Move servo to 90 degrees delay(1000); // Wait 1 second }
Example
This example shows how to sweep a servo motor back and forth between 0 and 180 degrees smoothly.
arduino
#include <Servo.h> Servo myServo; void setup() { myServo.attach(9); // Attach servo to pin 9 } void loop() { for (int angle = 0; angle <= 180; angle += 1) { myServo.write(angle); // Move servo to angle delay(15); // Wait for servo to reach position } for (int angle = 180; angle >= 0; angle -= 1) { myServo.write(angle); delay(15); } }
Output
Servo motor moves smoothly from 0° to 180° and back repeatedly.
Common Pitfalls
Common mistakes when using the Servo library include:
- Not calling
attach()beforewrite(), which means the servo won't move. - Using pins that do not support PWM or servo control (usually pins 9 and 10 are safe).
- Trying to control multiple servos without enough power supply, causing erratic behavior.
- Setting angles outside 0-180 degrees, which can damage the servo.
arduino
// Wrong: Writing angle before attaching servo #include <Servo.h> Servo myServo; void setup() { myServo.write(90); // Wrong: servo not attached yet myServo.attach(9); } void loop() {} // Right: #include <Servo.h> Servo myServo; void setup() { myServo.attach(9); // Attach first myServo.write(90); // Then write angle } void loop() {}
Quick Reference
| Function | Description |
|---|---|
| #include | Include the Servo library |
| Servo servoName; | Create a servo object |
| servoName.attach(pin); | Attach servo to Arduino pin |
| servoName.write(angle); | Set servo angle (0-180 degrees) |
| servoName.detach(); | Release the servo control |
Key Takeaways
Always include
#include <Servo.h> and create a Servo object before use.Attach the servo to a pin with
attach() before sending angle commands.Use
write() to set the servo angle between 0 and 180 degrees safely.Avoid controlling servos on unsupported pins or without sufficient power.
Detach servos with
detach() when no longer controlling them to save power.