Simple Control Loop

Hi, I am trying to control six servos for an experiment I am running. Each servo is connected to a spring simulating a load, and I want each servo to deflect from the neutral position to 90 degree deflection and back to neutral until i shut the system off. I have no experience when it comes to serial port servo control, and haven’t been able to make much sense of what I have read on these forums. I would prefer to use MATLAB as I am most comfortable with the syntax. Has anyone generated a code that will do something similar to what I am trying to accomplish, or can anyone give me a few pointers?

I’ve been messing around with this code that was posted: … oveServo.m

but I am getting an error message with the fopen command. I will keep trying but any help would be greatly appreciated!

You can totally do something like that using Matlab.

What is the error message you’re getting? And what com port is your servo controller connected to?


Hi Adam,

I’m not sure what was going on earlier but I got the “moveServo.m” file to work. It’s very sluggish, when I type say for instance “moveServo(0,4000)” into my workspace, it takes about 30 seconds for the servo to move, any way to get rid of the delay?

Here’s my logic for the rest of the code I will need to write:

use this line from the moveServo.m file:
fwrite(ser1, [128, 1, 4, s, binvec2dec(bitget(x,8:13)), binvec2dec(bitget(x,1:7))]);
to first deflect the servo to x=4000, then back to x=3000.

This will be inside a while loop that will run continuously until I stop the code.

Now that I talk it over some, it seems a lot easier to handle…I do have another question though, can I control the speed of the loop so the servo completes one cycle (from x=3000 to x=4000 and back to x=3000) every two seconds or so? I just don’t want the servo blazing saddles on rotation for fear the data I am gathering from this might be effected.


That does sound like an unusually long delay, but I suspect that’s just the time it takes Matlab to compile your code and open the port. If it takes that long in between calling the fwrite command each time your loop gets to it and seeing the servo move each time through your loop something is really wrong!

To slow your loop down you can add a pause command. “pause” by itself will wait until you press a key, which is very handy for debugging. “pause(0.5)” will pause your code for half a second, then continue.


Thanks for all your help, Adam! I’ve got it under control from here, and messed around with my code a little so the only delay is when I first start the code and the COM port is opened.

Thanks again!