Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

Electronics Projects: How to Program a Servo in PBASIC

To create motion in your electronics project, you can add a very useful device, called a servo, which lets you control mechanical motion with a BASIC Stamp program. A servo is a special type of motor that is designed to rotate to a particular position and hold that position until told to rotate to a different position. Hobby servos are frequently used in radio-controlled vehicles, but there are many other uses for servos.

The BASIC Stamp Activity Kit comes with a servo that you can use to learn how to write programs that control servos. You can also purchase servos directly from Parallax or from most hobby stores.

image0.jpg

The easiest way to control a servo from a BASIC Stamp microcontroller is to use the PULSOUT command. This command sends a pulse of any duration you specify to an I/O pin of your choosing. The syntax of this command is as follows:

PULSOUT pin, duration

You specify the duration in units of two microseconds. A microsecond is one-millionth of a second. There are one thousand microseconds in a millisecond. Thus, to send a 1.5 ms pulse with the PULSOUT command, you must specify 750 as the duration, like this:

PULSOUT 0,750

Here, a 1.5 ms pulse is sent to pin 0.

Here are the PULSOUT duration values you should use for a typical hobby servo for various angles.

Angle Duration Angle Duration
0 250 95 778
5 278 100 806
10 306 105 833
15 333 110 861
20 361 115 889
25 389 120 917
30 417 125 944
35 444 130 972
40 472 135 1000
45 500 140 1028
50 528 145 1056
55 556 150 1083
60 583 155 1111
65 611 160 1139
70 639 165 1167
75 667 170 1194
80 694 175 1222
85 722 180 1250
90 750

For example, to move the servo on pin 0 to 75°, use this command:

PULSOUT 0,667

Remember that to hold its position, a servo needs a constant stream of pulses approximately 20 ms apart. Thus, PULSOUT commands are usually contained in either DO loops or FOR-NEXT loops. For example, here’s a bit of code that keeps the servo on pin 0 at 45° indefinitely:

DO
 PULSOUT 0,500
 PAUSE 20
LOOP

Here is complete program that moves the servo to 45° when SW1 (a pushbutton on pin 14) is pressed and 135° when SW2 (a pushbutton on pin 10) is pressed.

' Servo Control Program
' Doug Lowe
' July 15, 2011
'
' This program moves a servo to one of two when SW1 is pressed
' and returns the servo to center position when SW2 is pressed.
' {$STAMP BS2}
' {$PBASIC 2.5}
Servo PIN 0
SW1  PIN 14
SW2  PIN 10
Position VAR Word
Position = 500
DO
 IF SW1 = 1 THEN
  Position = 500
 ENDIF
 IF SW2 = 1 THEN
  Position = 1000
 ENDIF
 PULSOUT Servo, Position
 PAUSE 20
LOOP
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.