I successfully got the Memsic 2125 Accelerometer to work on my Netduino, so I decided to take a crack at controlling a servo by measuring Tilt. I'm sure I could do a lot to make this more efficient but I just wanted to get this working first:
Below is the code I used (I plan on doing a lot more work to get this going right. Once I do, I will properly comment my code and clean things up to make it more user friendly.):
using System; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using SecretLabs.NETMF.Hardware; using SecretLabs.NETMF.Hardware.Netduino; namespace Memsic { public class Program { static int count = 0; static uint _lastposition = 0; static InputPort Xin = new InputPort(Pins.GPIO_PIN_D2, false, Port.ResistorMode.Disabled); static InputPort Yin = new InputPort(Pins.GPIO_PIN_D3, false, Port.ResistorMode.Disabled); static PWM ServoY = new PWM(Pins.GPIO_PIN_D9); public static void Main() { while (true) { int X = TiltToServoPulse(GhettoTilt(Xin)); int Y = TiltToServoPulse(GhettoTilt(Yin)); MoveServo(ServoY, (uint)Y); //Debug.Print("X:" + X + "," + "Y: " + Y); } } //Read the specified port and grab some values to calculate Ghetto Tilt. static int GhettoTilt(InputPort axe) { count = 0; // Loop until pin reads a low while (axe.Read() == true) { } // Loop until pin reads a high while (axe.Read() == false) { } // Loop until pin reads a low and count while (axe.Read() == true) { if (axe.Read() == false) { break; } count += 1; } count = count - 21; return count; } static void MoveServo(PWM whatservo, uint whereto, int sleep = 0) { if (_lastposition == whereto) { return; } uint HowLong = 0; if (whereto > 2000 || whereto < 1000) { return; } whatservo.SetPulse(20000, whereto); if (_lastposition == 0) { HowLong = 300; } else { HowLong = _lastposition > whereto ? (_lastposition - whereto) / 3 : (whereto - _lastposition) / 3; } Debug.Print("" + HowLong); Thread.Sleep((int)HowLong); whatservo.SetPulse(0, whereto); _lastposition = whereto; if (sleep != 0) { Thread.Sleep(sleep); } } static int TiltToServoPulse(double Tilt) { double pulse = 0; Tilt = Tilt - 1; double calc1 = Tilt / 18; pulse = (calc1 * 1000) + 1000; return (int)pulse; } } }
..and a video of the results:
http://www.youtube.com/watch?v=xTijhSgqMfM
Jason