Bird
0
0
Arduinoprogramming~5 mins

Servo motor control with Servo library in Arduino

Choose your learning style9 modes available
Introduction

Servo motors let you move things to specific angles easily. The Servo library helps you control these motors with simple commands.

You want to open or close a small door automatically.
You need to move a robot arm to certain positions.
You want to control the steering of a small car.
You want to make a dial or pointer move to show a value.
Syntax
Arduino
include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(pinNumber); // Connect servo to a pin
}

void loop() {
  myServo.write(angle); // Move servo to angle (0-180)
  delay(timeInMilliseconds); // Wait for servo to reach position
}

Use attach() to connect the servo to a pin.

write() moves the servo to an angle between 0 and 180 degrees.

Examples
This moves the servo to 90 degrees and waits 1 second.
Arduino
#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(9); // Attach servo to pin 9
}

void loop() {
  myServo.write(90); // Move servo to middle position
  delay(1000); // Wait 1 second
}
This smoothly moves the servo from 0 to 180 degrees in steps of 10.
Arduino
#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(10); // Attach servo to pin 10
}

void loop() {
  for (int angle = 0; angle <= 180; angle += 10) {
    myServo.write(angle); // Move servo from 0 to 180 in steps
    delay(500); // Wait half a second
  }
}
Sample Program

This program moves the servo motor to 0, then 90, then 180 degrees, pausing 1 second at each position.

Arduino
#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(9); // Connect servo to pin 9
}

void loop() {
  myServo.write(0); // Move to 0 degrees
  delay(1000); // Wait 1 second
  myServo.write(90); // Move to 90 degrees
  delay(1000); // Wait 1 second
  myServo.write(180); // Move to 180 degrees
  delay(1000); // Wait 1 second
}
OutputSuccess
Important Notes

Make sure your servo power supply can provide enough current.

Do not force the servo arm by hand while powered.

Use delays to give the servo time to reach the position before moving again.

Summary

The Servo library makes controlling servo motors easy.

Attach the servo to a pin, then use write() to set the angle.

Use delays to allow the servo to move smoothly between positions.