Servo Motor with Arduino

Back to Blog
Servo Motor with Arduino - Servo Motor with Arduino - Servo Motor with Arduino - Servo Motor with Arduino

Servo Motor with Arduino

Servo motors are widely used in Robots like robot arms and legs. Basically, a servo motor can operate upto 180-degree angle only. It will not rotate full revolution like a DC Motor.

A Servo motor can be controlled by degrees like 90 degrees, 180 degrees and 45 degrees. It uses PWM Signals to control the angle of the servo. Hence we need to use a servo motor on any one of the PWM pins.

Depending on the lifting capacity the servo motors can be used in different applications like Robotics, Solar Tracking, Automatic door opening and Obstacle detection robots.

We will be using Servo.h library for using our servo motor. The servo we are going to use is SG90 Servo.

Circuit Diagram:

Servo with Arduino_bbCode:

#include <Servo.h>

Servo myservo;    // create servo object to control a servo

int pos = 0;    // variable to store the servo position



void setup() {

  myservo.attach(9);  // attaches the servo on pin 9 to the servo object

}

void loop() {

  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees

    // in steps of 1 degree

    myservo.write(pos);              // tell servo to go to position in variable 'pos'

    delay(15);                       // waits 15ms for the servo to reach the position

  }

  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees

    myservo.write(pos);              // tell servo to go to position in variable 'pos'

    delay(15);                       // waits 15ms for the servo to reach the position

  }

}

In the above program, we used Servo.h library, which is included in the Arduino IDE itself. The Servo myservo() is the object to use many servos using the same functions. You can create more than 1 servo objects to use in the program. We need a variable to store the servo position. For this we use ‘pos’

int pos = 0;

To attach the servo we use myservo.attach() function. Here we attached servo at pin 9. So the parameter of this function will be

myservo.attach(9);

Using a ‘for loop’ we swing the servo to 180-degree step by step using servo.write() function. Similarly, in the next for loop, we swing the servo to 0 degrees. This will happen continuously because the code is in the main loop.

myservo.write(pos);

Here we created ‘myservo’ object. So we use ‘myservo’. If you named it for the different servo you can use that name.

If you want to move servo to a particular angle you can mention the angle directly inside the function,

Example:

myservo.wriite(90);

Share this post

Leave a Reply

Back to Blog