Learn how to control servos to achieve precise angular movements in Arduino projects.
A servo is a motor capable of precise angular control. Commonly used in robotics, servos allow positioning between 0º and 180º.
Servos are available in various sizes, with the SG90, MG90S, and MG996R being the most popular for hobby projects due to their cost-effectiveness.
These servos are perfect for various projects, including robotic arms, turrets, and more.
Internally, a servo uses a DC motor, reduction gears, and a potentiometer to control position based on a pulse width signal.
The servo responds to a PWM signal, where pulse widths correspond to specific angles:
The servo has three wires:
Connect the signal wire to any Arduino digital pin. For multiple voltage sources, ensure all GNDs are connected.
The following code makes the servo sweep from 0º to 180º and back:
#include
Servo myservo; // creates the servo object
int pos = 0; // servo position
void setup() {
myservo.attach(9); // attaches the servo to digital pin 9
}
void loop() {
// Sweep from 0 to 180º
for (pos = 0; pos <= 180; pos += 1)
{
myservo.write(pos);
delay(15);
}
// Sweep from 180 to 0º
for (pos = 180; pos >= 0; pos -= 1)
{
myservo.write(pos);
delay(15);
}
}