Sunday, March 4, 2012

Fun with Servos

I recently received 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
}  




1 comment:

  1. It is likely that noise from the servo motors was being coupled back into the Arduino via the power supply. I've run two servos at a time from one Arduino, even two regular size servos, not just minis like you have.

    In fact, at OlyMEGA we've built a bunch of little robots, each using two regular sized servos modified for continuous rotation for the wheels, so a lot more load than a free servo. We've run them powered from the Arduino's 5V power line, not a problem.

    I strongly suspect the electronics inside your servos aren't bypassed at the power supply voltage, or maybe you originally had the wires from the servo passing too close to the wires from your potentiometer. Or a ground loop problem.

    ReplyDelete