I was able to successfully control an HXT 900 servo using the Netduino board this evening and wanted everyone's thoughts on the code.
Basically, to figure out how to use the servo I read through a beginners guide to C# and the micro framework created by GHI located Here.
..after attempting to apply this code to the Netduino I realized that the logic for using the PWM.SetPulse method must be different on the Netduino, or I am just completely using it wrong...although was still able to get this to work. I know there are also different methods I could have used to get this to work, but this one really does seem to work well. I ran this servo for over an hour tonight without any issues.
using System; using System.Threading; using Microsoft.SPOT; using SecretLabs.NETMF.Hardware; using SecretLabs.NETMF.Hardware.Netduino; namespace Servo1 { public class Program { static PWM Servo1 = new PWM(Pins.GPIO_PIN_D9); static uint _left = 1000; static uint _center = 1500; static uint _right = 2000; static uint _lastposition = 0; public static void Main() { while (true) { MoveServo(Servo1,_left, 100); MoveServo(Servo1,_center,100); MoveServo(Servo1,_right, 100); } } //Move the servo between 1000(left) on 2000(right). static void MoveServo(PWM whatservo, uint whereto, int sleep = 0) { uint HowLong = 0; //exit the void to avoid servo damage if the value's are not within range. if (whereto > 2000 || whereto < 1000) {return;} //Begin sending the pulse to the servo. whatservo.SetPulse(20000, whereto); //if the lastposition of the servo is unknown (the default 0 value set above), //default the value to 300, otherwise calculate how longe the servo shoud run. if (_lastposition == 0) { HowLong = 300; } else { HowLong = _lastposition > whereto ? (_lastposition - whereto) / 3 : (whereto - _lastposition) / 3; } //continue sending the pulse using the howlong calculation. Thread.Sleep((int)HowLong); //stop the pulse. whatservo.SetPulse(0, whereto); //reset the last position after the move. _lastposition = whereto; //sleep the specified amount of time if applicable. if (sleep != 0) { Thread.Sleep(sleep); } } } }
ON a side note, the above code works for both 3.3v and 5v, but the servo seems to operate a lot smoother on 3.3v because of the "HowLong" calculation I am using.. a small adjustment to the calculation would fix this.
You see a video of the servo in action below:
http://www.youtube.com/watch?v=yUgzQP85qc4
Jason