Arduino R3 Basic Servo Project
This is a simple project showing how to connect an inexpensive servo to the Arduino
Wiring Diagram
- 1 x Arduino
- 1 x Servo
- 3 x Wires
- Yellow Wire – Servo Signal wire to tell the servo what angle to move to, servos typically have a range of 0degrees -> 180degress, however cheaper servos typically will only rotate to approx. 170degrees.
- Red Wire – Servo 5volts Power
- Black Wire – Servo Ground.
Calibrating the Servo
So, those little unhappy groan noises at either end of the servo’s arc: Although the code expects a servo that can rotate between 0º and 180º, that’s not always the case. So, we’ll adjust the code as needed so that it pauses only slightly at each extreme, and doesn’t make the little gear-grinding sound.
All you really need to do is modify the 0 and 180 numbers, moving both toward 90, until the switchback is instantaneous and the angry noises cease.
You can also use the example code I’ve uploaded below, which maps each extreme to a variable (min
& max
) so that you only have to change it in one place each time.
Arduino Sketch
#include <Servo.h> // adds the servo library to the sketch Servo myservo; // create servo object to control a servo int pos = 0; // variable to store the servo position int min = 0; // min servo position int max = 180; // max servo position int stepSize = 1; // servo step size int servoPin = 9; // servo pin to attach to int loopDelay = 5; // waits 15ms for the servo to reach the position int reset = 0; // if 0 servo lops back and forth, if 1 allows to reset servo to a position int resetPos = 90; // servo reset position if reset = 1 void setup() { myservo.attach(servoPin); // attaches the servo on pin 9 to the servo object } void loop() { if (reset==0) // if reset = 0 then back and forth otherwise reset position { for (pos = min; pos <= max; pos += stepSize) { // 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(loopDelay); // waits 15ms for the servo to reach the position } for (pos = max; pos >= min; pos -= stepSize) { // goes from 180 degrees to 0 degrees myservo.write(pos); // tell servo to go to position in variable 'pos' delay(loopDelay); // waits 15ms for the servo to reach the position } } else { myservo.write(resetPos); // reset servo position to a value } }