Before we get to the code, let's understand servos first.
The signal to control them is a positive pulse between 0.75 and 2.25ms long, followed by a 20ms 'off' or 0V 'pulse'.
In practice, I've found the off time can be anything from 10ms to 80ms with out affecting operation.
The important part is the short positive pulse duration.
0.75ms wll send the servo fully clockwise; 1.5ms will centre it and 2.25ms will be fully anticlockwise.The actual number of
degrees which it turns through for these values depends a lot on the servo itself. The one I'm using for testing turns about 180
degrees.
NOTE that you have to keep sending these signals all the time!! You don't just do it once.
let's just do a really simple test first. try this code... you will have to substitute your pin number instead of my C.1 (I only use 8 pin types)
Code: Select all
looper1:
PULSOUT C.1,150 'the 150 is 1.5ms
PAUSE 20 '20 ms 'off' time
goto looper1
You'll notice that you cannot turn the servo by hand - it is held in position.
You might like to try changing the PAUSE to 50 and confirm that it still works - but it is easier to turn by hand, signifying the
signal is not 'holding' it as well as 20ms does.
The next thing to know about servos, is that they turn as fast as they can in response to a change in the control signal pulse
length.
You can try this code to see this... (the 2 seconds is just a time I chose - it has no significance). I introduce a variable 'k' to
count the number of loops.
Code: Select all
symbol k=w0 'a counter
looper1:
'put it at one end for 2 secs (100x20ms)
for k=1 to 100
pulsout C.1,75 'fully CW
pause 20
next k
'now swing to the other end for 2 secs
for k= 1 to 100
pulsout C.1, 225
pause 20
next k
goto looper1
In order to slow them down, we have to 'step' through the pulse lengths we send out. So if we start at 75 and then increase it
'slowly' the servo will turn slowly.
Code: Select all
symbol k=w0
looper1:
'put it at one end for 2 secs (100x20ms)
for k=1 to 100
pulsout C.1,75 'fully CW
pause 20
next k
'now swing to the other end SLOWLY
k=75
moveit:
inc k
if k>225 then looper1
pulsout C.1, k
pause 20
goto moveit
To go even more slowly, you can just repeat each pulsout, without changing the pulse duration.
............
moveit:
inc k
if k>225 then looper1
pulsout C.1, k
pause 20
pulsout C.1, k
pause 20
goto moveit
I hope these bits of code help you get it working. I'd suggest writing the code for just one servo and get it to do what you want,
and then adding the other servos.
I'm not sure why you need to 'remember' the previous state of the servo - you already know it because you are sending out the
pulses of that length. You don't need to know where you are just where you want to get to !