How to Control Servo Motors With an Arduino

4.4K561

Intro: How to Control Servo Motors With an Arduino

This miniature project will show you how to control a servo motor with an Arduino, but first you need to know what a servo motor actually is!

Servo motors are special types of motors that don't spin around in a circle, but move to a specific position and stay there until you tell them to move again. Servos usually only rotate 180 degrees.

There is a servo library, which is what allows us to control them with an Arduino.

STEP 1: What You Will Need!

For today's project you will need:

1x Servo Motor

1x Arduino Board

1x Breadboard

1x Jumper Wires

1x Potentiometer

STEP 2: Wiring the Potentiometer

The potentiometer has three pins:

- Wire the one on the left to GND (Ground)

- Wire the one on the right to 5V

- Wire the middle pin to Analog 0

STEP 3: Wire Your Servo

The servo has three pins:

- the one on the left needs to be wired to GND

- the one in the middle needs to be wired to 5v

- the one on the right needs to be wired to digital pin 9

STEP 4: Copy and Paste This Code Into Your Arduino IDE

#include
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
val = analogRead(potpin); // reads the value of the
// potentiometer (value between
// 0 and 1023)
val = map(val, 0, 1023, 0, 179); // scale it to use it with
// the servo (value between 0 and
// 180)
myservo.write(val); // sets the servo position according
// to the scaled value
delay(15); // waits for the servo to get there
}

Comments

Great job!

Helpful comment: I think that you for got to name the Servo in the #include (e.g. #include<Servo.h>)

I am new to Arduino and I had to do some research to figure out why the code kept giving me errors (without the Servo naming) which was really quite educational for me.

Thank you for this instructable.