### Lab – Servo Motor Control with Arduino

02Oct10

I hooked up a force-sensitive resistor with a 10k ohm resistor as my analog input, and a RC servo motor to a breadboard and Arduino microcontroller to see how analog input can control a servo motor. This was a really fun lab.

The FSR sensor returned a range of values 0 to 800, but when I mapped the full range of values to the servo motor’s angles, the wheel only spun 3/4 of the way around. So, then I tried using a range of 0 to 500, and that worked much better and made the wheel spin 360 degrees! I attached little red and green wires to the top of the wheel to show the “spin”. This code will tell the microcontroller to move the servo as the value of the FSR changes:

```int servoPin = 2;     // Control pin for servo motor
int minPulse = 500;   // Minimum servo position
int maxPulse = 2500;  // Maximum servo position
int pulse = 0;        // Amount to pulse the servo

long lastPulse = 0;    // the time in milliseconds of the last pulse
int refreshTime = 20; // the time needed in between pulses

int analogValue = 0;  // the value returned from the analog sensor
int analogPin = 0;    // the analog pin that the sensor's on

void setup() {
pinMode(servoPin, OUTPUT);  // Set servo pin as an output pin
pulse = minPulse;           // Set the motor position value to the minimum
Serial.begin(9600);
}

void loop() {
Serial.println(analogValue);

pulse = map(analogValue,0,500,minPulse,maxPulse);
// convert the analog value to a range between minPulse and maxPulse

// pulse the servo again if the refresh time (20 ms) has passed:
if (millis() - lastPulse >= refreshTime) {
digitalWrite(servoPin, HIGH);   // Turn the motor on
delayMicroseconds(pulse);       // Length of the pulse sets the motor position
digitalWrite(servoPin, LOW);    // Turn the motor off
lastPulse = millis();           // save the time of the last pulse
}
}
```

#### 3 Responses to “Lab – Servo Motor Control with Arduino”

1. 1 Terence Roe

Hi
Thanks for interesting topic on servo and programming. I have a question ! i would like to bring the servo arm back to its orignal position after 2 minutes how would i do that in the program.

only started progamming a couple of weeks ago so still a beginner.

Thanks for the article

Regards Terence

2. 2 suzkita

Check out this tutorial about servo motors and programming the microcontroller – part 4.
http://itp.nyu.edu/physcomp/Labs/Servo#toc4
You will need to map the values of your sensor to your servo angles using a local variable called servoAngle().
Good luck!

3. 3 derek E

can a 360 servo be set to move like a 180. ex : i want it ti pos 36 then to pos 360