Controlling Servos Motors with Processing


Think about a Servo motor as a geared DC motor with a potentiometer attached to it. The motor "knows" where it is in the rotation. When you sent a message to the motor you send a pulse, the motor then interprets that pulse and moves to the corresponding spot.
Like a pot, the motor does not rotate a full 360 degrees. Not all servos are the same, but most only go 180 degrees. They are often used in robots, toy planes and toy cars. It's hard to find discarded servos, they are not that common, but if you see a toy car in the trash you should pick it up for sure.
Yes, there are continuos servos, although "standard servos" are more common. In a continuos servo you can control speed but not location. With a little creative destruction you can open up a standard servo and take out the limiter, making it continuos.

To test the Servo you can plug it directly into into the arduino. Red to 5v power, black to ground, white to digital pin 10. Notice that pin 10 has a PWM next to it? That stands for Pulse Width Modulation the arduino uses different frequency pulses to communicate with the circuitry in the servo.

To get the servo running in Processing you will need to return to the arduino environment.
go under Sketchbook - examples - Firmata - servoFirmata
Upload this new code to the arduino. The servoFirmata uses the arduino's "Servo" library, which is awesome because it handles a heap load of the math for you. This means all we have to supply is a value between 1 and 180 and the servo will turn to that point.

With the servoFirmata on the arduino go back to Processing and run this "hello servo world" code.


//This code requires the arduino to be loaded with ServoFirmata.
import processing.serial.*;
import cc.arduino.*;
Arduino arduino;
int servoPin = 10; // Control pin for servo motor
void setup(){
size (180, 50);
arduino = new Arduino(this, Arduino.list()[0]);
arduino.pinMode(servoPin, Arduino.OUTPUT);
// note - we are setting a digital pin to output
}
void draw(){
arduino.analogWrite(servoPin, mouseX); // the servo moves to the horizontal location of the mouse
}

The servoFirmata code in will work with either port 9 or 10. If you want more than 2 servos you can alter the ServoFirmata code in the Arduino environment. You can add up to 6 - make sure you use port 3, 5, 6, 9, 10 , or 11 (the PWM ports).

The ServoFirmata is a scaled back version of firmata that only allows you to address servos and nothing else. It's easy enough to add the servo library to the standard_firmata making an uber_Firmata. Here's an example.