Servo Motor

Servo are smart motors widely used in robotics.
The hobbyist ones usually look like this:

Try circuit #8 from the manual. Load the example.
Fortunately there is a library for Arduino that lets us control the servo with few lines of code.

-Don’t forget to include the library:

#include <Servo.h>

-Our servo has a range of 180 degrees.
-The servo signal must be connected to an analog enabled output, the ones with the ~tilda.

This sketch requires the previous circuit with the potentiometer and connects the analog input with the analog output.

Note that the servo accepts values from 0 to 180 (degrees) while the analog input detect values from 0 to 1024. So I need a map function to scale one range onto another:

#include <Servo.h>

int sensorPin = 0;    // select the input pin for the potentiometer

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created
int pos = 0;    // variable to store the servo position

void setup()
  pinMode(sensorPin, INPUT);    
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object

void loop()
  int sensorValue = analogRead(sensorPin);    
  pos = map(sensorValue, 0, 1024, 0, 180);
// tell servo to go to position in variable 'pos'

Try to connect it to a potentiometer!

Posted in

Post a comment