How to Program a Servo Motor

Servo motors are a type of motor that can only rotate from 0-180 degrees. This motor can be very useful such as making locks for doors or a switch.

Requirements

  • Arduino
  • 3 wires
  • Servo motor

How does it work

Servo motors rely on PWM output to receive commands of what position the shaft in the motor should move to. The motor moves, by position, 0 – 180 degrees. There are alternatives to standard servos which are continuous servo motors that can move 360 degrees but for this tutorial, we’re going to use standard 0 to 180 degrees motors.

Schematic

Code

#include <Servo.h>

Servo myservo;

Call the library and instantiate the Servo object.

void setup() {

    myservo.attach(3);

}

The Servo motor library allows us to use initiate the servo motor my calling the “attach” method and calling the PWM digital pin which the servo is connected to.

void loop() {

    for(int x = 0;x<=180;x++) //goes from 0 to 180
    {
      myservo.write(x);
      delay(15);
    }
    for(int y = 180;y>=0;y--)// 180 - 0
    {
      myservo.write(y);
      delay(15);
    
    }
}

What this does is that it uses two for loop to spin from position 0 to 180 and back to 0. After it finishes the 180, it makes a full rotation and returns to 0. You can’t control the full rotation of the motor.

Final Code

#include <Servo.h>

Servo myservo;

void setup() {

    myservo.attach(3);

}

void loop() {

    for(int x = 0;x<=180;x++)
    {
      myservo.write(x);
      delay(15);
    }
    for(int y = 180;y>=0;y--)
    {
      myservo.write(y);
      delay(15);
    
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *