Arduino Servo Motor Code Using the Servo Library
hardMotorsArduino (C++)
A servo turns to an exact angle between 0° and 180° — used in robot arms and gates.
The question
A servo motor's signal wire is on pin 10. Using the Servo library, move it to 90°, wait 1000 ms, move it to 135°, wait 1000 ms, and repeat.
The sketch
sketch.ino
#include <Servo.h>
Servo motor;
void setup() {
motor.attach(10);
}
void loop() {
motor.write(90);
delay(1000);
motor.write(135);
delay(1000);
}Wiring
Servo: brown → GND, red → 5V, orange (signal) → pin 10.
How it works
- 1#include <Servo.h> and Servo motor; create a servo object.
- 2motor.attach(pin) connects it to the signal pin.
- 3motor.write(angle) turns it to that angle; the delay gives it time to get there.
Common mistakes
- Using analogWrite for a servo — it needs the Servo library's special pulses.
- Powering a large servo from the Arduino's pin instead of the 5V supply.
Now solve a similar question yourself
A new Arduino question every time, checked instantly.
