Sunday, March 4, 2012

Fun with Servos

Hacktronics recently sent me two HXT900 servos to play with. I used the sample servo code included in the Arduino IDE, that allows me to control the servo position with a potentiometer.

The pot is connected to the arduino, with the center wiper connected to Analog 0, and the outside connections to +5 and Gnd., respectively.

The servo initially gave us trouble, till Wild Bill on the Arduino.cc forum pointed out the servo needs it's own power supply. The Arduino can't provide enough power to operate it reliably, and could possibly damage the Arduino (thankfully it didn't).

So, we connected the orange wire on the servo to Arduino pin 9, the servo red wire to the + of two AA batteries in series, and the servo brown wire, plus the AA battery pack negative, to Arduino ground. We then loaded the following sketch, and had instant success!

// Controlling a servo position using a potentiometer (variable resistor)
// by Michal Rinott

#include "servo.h"

Servo myservo;  // create servo object to control a servo

int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

void setup()
{
  Serial.begin(9600);          //  setup serial
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
//  Serial.println(val);
  val = map(val, 0, 1023, 0, 179);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);    // sets the servo position according to the scaled value
//  Serial.println(val);
  delay(15);                           // waits for the servo to get there
}