# How to control a servo motor

using the audio card of your PC

Servo motors are controlled by a simple 50Hz pulse-width mechanism. This means that with a simple hack one can control two servos with a stereo pc audio card using GNU/Octave.

The following function returns a square wave with a 50Hz period with duty cycle equal to `x`

```function y=square(x)
fs=44100;
freq=50;
t=0:1/fs:1/50;
y=(x+sin(2*pi*freq*t))./abs(x+sin(2*pi*freq*t));
end
```
Here's some examples: For a 45 degree rotation the typical wave forms used are given by the widths (1.5ms, 1ms, 2ms), respectively, for (center, left, right). The width of the signal determines the position of the servo motor. Angle resolution is manufacture dependent and typical widths varies between 0ms and 4ms (full left or full right). Check this video by Norbert Heinz, a truly knowledge free spirit.

Here's some pics of my latest experience   It actually worked well but the mechanical robustness of this system is low (servos quality improves it, not the 3eurs servo motors that I have ;) ). The math involve to make this type of robot to work is not trivial (I have some programming to control it, see video), and the mechanical improvements needed are hard enough to convince me not to take another run on the project. At least for now. Here's the video.

In order to control the servo motor a series of pulses must be generated. The following function returns a square function with a duty cycle `x`. x=-1 equals, 0ms x=0 equals 2ms x=1 equal 4ms.

```function y=f(x)
fs=44100;
freq=50;
t=0:1/fs:1/50;
x=1-(2*x+2)/50;
y=(x+sin(2*pi*freq*t))./abs(x+sin(2*pi*freq*t));
end
```

Given a vector of positions the next function returns the corresponding list of control servo pulses

```function retval=g(t)
n=length(t);
retval=[];
for i=1:n
retval=[retval f(t(i))];
end
end
```

The pulses for both channels are written to a WAV file using the `wavwrite` command

```wavwrite([u' v'],44100,16,"test.wav")
```

where `u` is left, `v` right, bits per sample equals 16 and sample rate 44100. Use VLC to play it.

Happy hacking!

Palavras chave/keywords: servo motor, pc, audio card  