Working with Servos
Simple Servos
A servo is a motor whose rotation can be controlled precisely. Most servos only have a set rotation from around 0 - 270 degrees so they don't do a full rotation or keep turning in one direction. But the benefit of them is that you can get a precise position within their range. To control the position of the servo you pulse for a very precise time in microseconds, this tells the servo which position to move to for example 500 microseconds will set the servo to 0 degrees and 2500 will set the servo to 270 degrees. The servo then moves to the correct location.
Arduino code for controlling servo with an analog sensor (i.e. a slider)
The code below is a very simple example of how to control a servo with an analog input. Servo control to pin 10 and sensor to pin 2.
/**
servo mover
completed at 12:00 4/11/2008
Created by pete-rogers.co.uk
Servo mover moves a servo dependent upon a analog sensor signal from 0 - 1024
Connectors:
Servo to pin 10
Analog sensor to pin 2
**/
//constants
int servoPin = 10;
int sensorPin = 2;
int lower = 1700;
int higher = 2450;
//configerable
int inExtreme = 2500;
int outExtreme = 500;
int sensorNum;
int val;
void setup(){
Serial.begin(9600);
}
void loop (){
delay(20);
Serial.println(val);
checkSensor();
servoMove();
}//end loop
//checks the sensor and adjusts to servos range
int checkSensor(){
val = analogRead(sensorPin);
val = val * 2;
val = val + 550;
if(val < lower){
val = lower;
}
if (val > higher){
val = higher;
}
}
void servoMove(){
digitalWrite(servoPin, HIGH); // Turn the motor on
delayMicroseconds(val); // Length of the pulse sets the motor position
digitalWrite(servoPin, LOW); // Turn the motor off
}//end servoMove