RA Code: Moving servos with potentiometers

Today we are going to move our three servos (yes, they finally arrived!) using three 10K ohm potentiometers.

Reading the voltage in each potentiometer, using analog inputs, we will change the duty cycle of each servo, changing how much time is the PWM in high level and how much in low level. (If you don't know what I am talking about, have a look here).

First of all, set up this circuit in the prototyping board: (click on the image to see a larger version)

Now, read the code below, understand what will happen when it runs in the Arduino, tune it as you like, and transfer it to the board.

Important note: The values for minPulse, maxPulse and refreshTime will be servo dependant, you should find suitable values for your gear.

byte numServos=3; // Number of servos to use
int minPulse[3] = {400, 400, 400}; // Pulse for minimum servo position (microseconds)
int maxPulse[3] = {2050, 2050, 2050}; // Pulse for maximum servo position (microseconds)
byte refreshTime[3] = {20, 20, 20}; // Time needed in between pulses (milliseconds)
byte servoPin[3] = {9, 10, 11}; // Pins where servos are
int analogValue[3] = {0, 0, 0}; // To store potentiometers values
int pulse[3]={0, 0, 0}; // Pulse to be sent to servos
long lastPulse[3] = {0,0,0}; // Time in milliseconds when the last pulse started
byte analogPin[3] = {0, 1, 2}; // Pins where potentiometers are

void setup() {
  byte i=0;
  for(i=0;i<numServos;i++)
  {
    pinMode(servoPin[i], OUTPUT);  // Set servo pin as an output pin
  }
  Serial.begin(9600);
}

void loop() {
  int i=0;
  for(i=0;i<numServos;i++)
  {
    // Read potentiometers values
    analogValue[i] = analogRead(analogPin[i]);
pulse[i]=map(analogValue[i],0,1023,minPulse[i],maxPulse[i]);
    // And send control signal to servos
    if (millis() - lastPulse[i] >= refreshTime[i]) 
    {
      digitalWrite(servoPin[i], HIGH);   // Turn the motor on
      delayMicroseconds(pulse[i]);       // Length of the pulse sets the motor position
      digitalWrite(servoPin[i], LOW);    // Turn the motor off
      lastPulse[i] = millis();           // save the time of the last pulse
    }
  }
  // Send feedback through serial port
  for(i=0;i<numServos;i++)
  {
    Serial.print(" Servo ");
    Serial.print(i);
    Serial.print(" pulse: ");
    Serial.print(pulse[i]);
  }
  Serial.println("");
}

Now, when this runs in the Arduino, you should have three servos, that move each one as you change the corresponding potentiometer value. We will use this to try out our robotic arm, to see the maximum and minimum values of pulse that make each servo reach the lower and upper limits that we want our arm to reach, that will strongly depend of the mechanical design of the arm.

But we'll go deeper into that later, now just play for a while and start thinking what will you use as "bones", how will you join the servos to make all this look like an arm.

I already have my arm, so I'll post some pictures round here soon :-)