How to Control Servo Motors With an Arduino
by ArduinoT in Circuits > Arduino
4520 Views, 56 Favorites, 0 Comments
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.
What You Will Need!
For today's project you will need:
1x Servo Motor
1x Arduino Board
1x Breadboard
1x Jumper Wires
1x Potentiometer
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
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
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
}