bs1Appnotes

download bs1Appnotes

of 126

Transcript of bs1Appnotes

  • 8/7/2019 bs1Appnotes

    1/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 71

    BASIC Stamp I Application Notes

    1

    1: LCD User-Interface Terminal

    Introduction. This application note p resents a pr ogram in PBASIC thatenables the BASIC Stamp to op erate as a simple u ser-interface term inal.

    Background. Many systems use a central host computer to controlremote functions. At various locations, users communicate with themain system v ia small terminals that d isplay system statu s and acceptinpu ts. The BASIC Stamp s ease of pr ogram ming and built-in su pp ortfor serial communications make it a good candidate for such user-interface applications.

    The liquid -crystal d isplay (LCD) used in this p roject is based on th epopular Hitachi 44780 controller IC. These chips are at the heart of LCDs ran ging in size from tw o lines of four characters (2x4) to 2x40.

    How it works. When power is first applied, the BASIC programinitializes the LCD. It sets the d isplay to p rint from left to righ t, andenables an underline cursor. To eliminate any stray characters, the

    pr ogram clears the screen.

    After initialization, the p rogram enters a loop w aiting for th e arrival of a character via the 2400-baud RS-232 interface. When a characterarr ives, it is checked against a sh ort list of special characters (backspace,control-C, and return ). If it is not one of these, the p rogram pr ints it onthe d isplay, and re-enters the w aiting-for-data loop .

    If a backspace is received, the prog ram mov es the LCD cur sor back one

    Schematic to accompany program TERMINAL.BA S.

    PIC1 6 C5 6

    01234567

    +5V Vin

    GNDBASIC STAMP

    EEPR

    OM

    (C) 1992 Parallax, Inc.

    PC

    2 3 1

    10k(contrast)

    6 5 7 8 9 10

    +510k

    1k

    SWITCHES 03

    22k1k

    414131211

    SERIAL IN

    SERIAL OUT

    Vdd Vo R/WVss

    DB4DB5DB6DB7

    DB0 DB1 DB2 DB3ERS

  • 8/7/2019 bs1Appnotes

    2/126

  • 8/7/2019 bs1Appnotes

    3/126

  • 8/7/2019 bs1Appnotes

    4/126

    Page 74 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    BASIC Stamp I Application Notes

    Symbol Sw_0 = pin0 ' User input switches

    Symbol Sw_1 = pin1 ' multiplexed w/LCD data lines.Symbol Sw_2 = pin2Symbol Sw_3 = pin3

    ' Set up the Stamps I/O lines and initialize the LCD.begin: let pins = 0 ' Clear the output lines

    let dirs = %01111111 ' One input, 7 outputs.pause 200 ' Wait 200 ms for LCD to reset.

    ' Initialize the LCD in accordance with Hitachis instructions for 4-bit interface.

    i_LCD: let pins = %00000011 ' Set to 8-bit operation.pulsout E,1 ' Send data three timespause 10 ' to initialize LCD.pulsout E,1pause 10pulsout E,1pause 10let pins = %00000010 ' Set to 4-bit operation.pulsout E,1 ' Send above data three times.pulsout E,1

    pulsout E,1let char = 14 ' Set up LCD in accordance withgosub wr_LCD ' Hitachi instruction manual.let char = 6 ' Turn on cursor and enablegosub wr_LCD ' left-to-right printing.let char = 1 ' Clear the display.gosub wr_LCDhigh RS ' Prepare to send characters.

    ' Main program loop: receive data, check for backspace, and display data on LCD.

    main: serin S_in,N2400,char ' Main terminal loop.goto bkspout: gosub wr_LCD

    goto main

    ' Write the ASCII character in b3 to LCD.wr_LCD: let pins = pins & %00010000

    let b2 = char/16 ' Put high nibble of b3 into b2.let pins = pins | b2 ' OR the contents of b2 into pins.pulsout E,1 ' Blip enable pin.

    let b2 = char & %00001111 ' Put low nibble of b3 into b2.let pins = pins & %00010000 ' Clear 4-bit data bus.let pins = pins | b2 ' OR the contents of b2 into pins.pulsout E,1 ' Blip enable.return

    ' Backspace, rub out character by printing a blank.

    1: LCD User-Interface Terminal

  • 8/7/2019 bs1Appnotes

    5/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 75

    BASIC Stamp I Application Notes

    1

    bksp: if char > 13 then out ' Not a bksp or cr? Output character.

    if char = 3 then clear ' Ctl-C clears LCD screen.if char = 13 then cret ' Carriage return.if char 8 then main ' Reject other non-printables.gosub backlet char = 32 ' Send a blank to displaygosub wr_LCDgosub back ' Back up to counter LCDs auto-

    ' increment.goto main ' Get ready for another transmission.

    back: low RS ' Change to instruction register.let char = 16 ' Move cursor left.gosub wr_LCD ' Write instruction to LCD.high RS ' Put RS back in character mode.return

    clear: low RS ' Change to instruction register.let b3 = 1 ' Clear the display.gosub wr_LCD ' Write instruction to LCD.high RS ' Put RS back in character mode.

    goto main' If a carriage return is received, wait for switch input from the user. The host' program (on the other computer) should cooperate by waiting for a reply before' sending more data.cret: let dirs = %01110000 ' Change LCD data lines to input.loop: let keys = 0

    if Sw_0 = 1 then xmit ' Add one for each skipped key.let keys = keys + 1if Sw_1 = 1 then xmit

    let keys = keys + 1if Sw_2 = 1 then xmitlet keys = keys + 1if Sw_3 = 1 then xmitgoto loop

    xmit: serout S_out,N2400,(#keys,10,13)let dirs = %01111111 ' Restore I/O pins to original state.goto main

    1: LCD User-Interface Terminal

  • 8/7/2019 bs1Appnotes

    6/126

    Page 76 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    BASIC Stamp I Application Notes

  • 8/7/2019 bs1Appnotes

    7/126

  • 8/7/2019 bs1Appnotes

    8/126

  • 8/7/2019 bs1Appnotes

    9/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 79

    BASIC Stamp I Application Notes

    1

    ' and linefeed.

    pause 2000 ' Wait 2 secondsgoto loop ' Do it forever.

    conv: low CLK ' Put clock line in starting state.low CS ' Select ADC.pulsout CLK, 1 ' 10 us clock pulse.let data = 0 ' Clear data.for i = 1 to 8 ' Eight data bits.let data = data * 2 ' Perform shift left.pulsout CLK, 1 ' 10 us clock pulse.

    let data = data + AD ' Put bit in LSB of data.next ' Do it again.high CS ' Deselect ADC when done.return

    2: Interfacing an A/D Convertor

  • 8/7/2019 bs1Appnotes

    10/126

    Page 80 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    BASIC Stamp I Application Notes

  • 8/7/2019 bs1Appnotes

    11/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 81

    BASIC Stamp I Application Notes

    1

    3: Hardware Solution for Keypads

    Introduction. This application note p resents a pr ogram in PBASIC that

    enables the BASIC Stamp to read a k eypad and display keyp resses ona liquid-crystal display.

    Background. Many controller applications require a keypad to allowthe user to enter nu mbers and comm ands. The usual way to interface akeypad to a controller is to connect inpu t/ outp ut (I/ O) bits to row an dcolumn connections on the keypad. The keypad is wired in a matrixarrangement so that wh en a key is pressed one row is shorted to one

    colum n. Its relatively easy to w rite a rou tine to scan the keyp ad , detectkeypresses, and determine which key was pressed.

    The trouble is that a 16-key pad requ ires a minimu m of eight bits (fourrows and four columns) to implement this approach. For the BASICStam p, with a total of only eight I/ O lines, this may not be feasible, evenwith clever m ultiplexing arrangements. And although the pr ogram-ming to scan a keyp ad is relatively simple, it can cut into th e Stamp s 255

    bytes of program m emory.

    An alternative that conserves both I/ O bits and pr ogram sp ace is to usethe 74C922 keypad decoder chip. This d evice accepts inp ut from a 16-key pad, performs all of the required scanning and debouncing, and

    PIC 1 6 C 5 6

    01234567

    + 5V Vi n

    GNDBASIC STAMP

    EEPROM

    (C) 1992 Parallax, Inc.

    PC

    2 3 1

    10k(contrast)

    65 7 8 9 10

    +5

    414131211

    10kall

    +5Matrix keypad (pressing

    a key shorts a rowconnection to a column)

    available

    1x16-character LCD module, Hitachi 44780 controller

    Vd d Vo R/WVss

    DB4DB5DB6DB7

    DB0 DB1 DB2 DB3ERS

    .1F

    1F

    74C922

    1

    2

    3

    4

    5

    6

    7

    8

    9

    18

    17

    16

    15

    14

    13

    12

    11

    10

    row 3

    row 4

    scan

    debounce

    col 4

    col 3

    gnd

    d0

    d1

    d2

    d3

    out enable

    data avail

    col 1

    col 2

    Vccrow 1

    row 2

    Schematic to accompanyprogram KEYPAD.BAS.

  • 8/7/2019 bs1Appnotes

    12/126

    Page 82 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    BASIC Stamp I Application Notes 3: Hardware Solution for Keypads

    outputs a data available bit and 4 output bits representing the

    number of the key pressed from 0 to 15. A companion device, the74C923, has the sam e features, but read s a 20-key pad and outp uts 5d ata bits.

    Application. The circuit shown in the figure interfaces a keypad andliqu id-crystal d isplay (LCD) mod ule to the BASIC Stamp , leaving tw oI/ O lines free for other pu rp oses, such as bidirectional serial commu ni-cation. As programmed, this application accepts keystrokes from 16

    keys and displays them in hexadecimal format on the LCD.

    When the u ser presses a button on the keypad , the corresponding hexcharacter app ears on the d isplay. When th e user has filled the disp layw ith 16 characters, the pr ogram clears the screen.

    The circuit m akes good use of th e electrical prop erties of the Stamp , theLCD mod ule, and th e 74C922. When th e Stamp is add ressing th e LCD,

    the 10k resistors p revent keyp ad activity from r egistering. The Stampcan easily drive its outpu t lines high or low regard less of the status of these lines. When the Stamp is not ad d ressing th e LCD, its lines areconfigur ed as inp uts, and the LCDs lines are in a high-imp edan ce state(tri-stated). The Stamp can then receive inpu t from the keyp ad w ithoutinterference.

    The pr ogram uses the button instruction to read the d ata-available line

    of the 74C922. The debounce feature of button is unnecessary in thisapplication because the 74C922 debounces its inputs in hardware;however, button provides a professional touch by enabling delayedauto-repeat for the keys.

    Program listing. This program m ay be down loaded from ou r Internetftp site at ftp.parallaxinc.com. The ftp site may be reached directly orthrou gh our w eb site at http :/ / ww w .parallaxinc.com.

    ' PROGRAM: Keypad.bas' The Stamp accepts input from a 16-key matrix keypad with the help of' a 74C922 keypad decoder chip.Symbol E = 5 ' Enable pin, 1 = enabledSymbol RS = 4 ' Register select pin, 0 = instruction

  • 8/7/2019 bs1Appnotes

    13/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 83

    BASIC Stamp I Application Notes

    1

    3: Hardware Solution for Keypads

    Symbol char = b1 ' Character sent to LCD.Symbol buttn = b3 ' Workspace for button command.Symbol lngth = b5 ' Length of text appearing on LCD.Symbol t emp = b7 ' Temporary holder for input character.

    ' Set up the Stamp's I/O lines and initialize the LCD.begin: let pins = 0 ' Clear the output lines

    let dirs = %01111111 ' One input, 7 outputs.pause 200 ' Wait 200 ms for LCD to reset.let buttn = 0let lngth = 0gosub i_LCDgosub clear

    keyin: let dirs = %01100000 ' Set up I/O directions.loop: button 4,1,50,10,buttn,0,nokey ' Check pin 4 (data available) for

    ' keypress.lngth = lngth + 1 ' Key pressed: increment position

    counter.let temp = pins & %00001111 ' Strip extra bits to leave only key data.if temp > 9 then hihex ' Convert 10 thru 15 into A thru F (hex).let temp = temp + 48 ' Add offset for ASCII 0.

    LCD: let dirs = %01111111 ' Get ready to output to LCD.if lngth > 16 then c_LCD ' Screen full? Clear it.

    cont: let char = temp ' Write character to LCD.gosub wr_LCD

    nokey: pause 10 ' Short delay for nice auto-repeat' speed.

    goto keyin ' Get ready for next key.

    hihex: let temp = temp + 55 ' Convert numbers 10 to 15 into A - F.goto LCD

    c_LCD: let lngth = 1 ' If 16 characters are showing on LCD,gosub clear ' clear the screen and print at left edge.goto cont

    ' Initialize the LCD in accordance with Hitachi's instructions' for 4-bit interface.i_LCD: let pins = %00000011 ' Set to 8-bit operation.

    pulsout E,1 ' Send above data three timespause 10 ' to initialize LCD.pulsout E,1pulsout E,1let pins = %00000010 ' Set to 4-bit operation.pulsout E,1 ' Send above data three times.pulsout E,1pulsout E,1let char = 12 ' Set up LCD in accordance w/

  • 8/7/2019 bs1Appnotes

    14/126

    Page 84 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    BASIC Stamp I Application Notes

    gosub wr_LCD ' Hitachi instruction manual.let char = 6 ' Turn off cursor, enablegosub wr_LCD ' left-to-right printing.high RS ' Prepare to send characters.return

    ' Write the ASCII character in b3 to the LCD.wr_LCD: let pins = pins & %00010000

    let b2 = char/16 ' Put high nibble of b3 into b2.let pins = pins | b2 ' OR the contents of b2 into pins.pulsout E,1 ' Blip enable pin.let b2 = char & %00001111 ' Put low nibble of b3 into b2.let pins = pins & %00010000 ' Clear 4-bit data bus.let pins = pins | b2 ' OR the contents of b2 into pins.pulsout E,1 ' Blip enable.return

    ' Clear the LCD screen.clear: low RS ' Change to instruction register.

    let char = 1 ' Clear display.gosub wr_LCD ' Write instruction to LCD.high RS ' Put RS back in character mode.return

    3: Hardware Solution for Keypads

  • 8/7/2019 bs1Appnotes

    15/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 85

    BASIC Stamp I Application Notes

    1

    4: Controlling and Testing Servos

    Introduction. This application note p resents a pr ogram in PBASIC that

    enables the BASIC Stamp to control pu lse-width pr opor tional servosand measure the pu lse width of other servo drivers.

    Background. Servos of the sort u sed in r adio-controlled airplanes arefind ing new app lications in h ome and indu strial automation, movieand them e-par k special effects, and test equ ipm ent. They simp lify thejob of moving objects in the realworld by eliminating much of the

    mechanical design. For a given sig-nal input, you get a predictableamoun t of motion as an outpu t.

    Figur e 1 show s a typical servo. Thethree wires are +5 volts, ground,and signal. The outp ut sh aft acceptsa w ide variety of prefabricated d isks

    and levers. It is dr iven by a geared-dow n motor and rotates through 90to 180 degrees. Most servos can ro-tate 90 degrees in less than a half second. Torque, a measure of theservos ability to overcome mechanical resistance (or lift weight, pullspr ings, pu sh levers, etc.), ran ges from 20 to more than 100 inch-ou nces.

    To make a servo m ove, conn ect it to a 5-volt pow er sup ply capable of

    delivering an am pere or m ore of peak current, and supp ly a positioning

    Figure 1. A typical servo.

    Figure 2. Schematic to accompany programSERVO.BA S.

    PIC 1 6 C 5 6

    01234567

    +5V Vi n

    GNDBASIC STAMP

    EEPROM

    (C) 1992 Parallax, Inc.

    PC

    2 3 1

    10k(contrast)

    65 7 8 9 10

    +510k

    1k

    Toggle Function

    414131211

    Servo signal in

    Servo signal out

    1x16-character LCD module, Hitachi 44780 controller

    Vdd Vo R/WVss

    DB4DB5DB6DB7

    DB0 DB1 DB2 DB3ERS

  • 8/7/2019 bs1Appnotes

    16/126

  • 8/7/2019 bs1Appnotes

    17/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 87

    BASIC Stamp I Application Notes

    1

    4: Controlling and Testing Servos

    of 10s. For m ost servos, this equates to a resolution of better than 1

    degr ee of rotation.

    The program is straightforwar d Stamp BASIC, but it d oes take advan-tage of a couple of the langu ages han dy features. The first of these is theEEPROM d irective. EEPROM ad d ress,data allows you to stu ff tables of data or text strings into EEPROM memory. This takes no additionalprogram time, and on ly uses the amount of storage required for thedata. After the sym bols, the first thing that the listing does is tuck a

    couple of text strings into the bottom of the EEPROM. When thepr ogram later needs to display status m essages, it loads the text stringsfrom EEPROM.

    The other featur e of the Stamps BASIC that th e p rogram exploits is theability to use comp oun d expr essions in a let assignm ent. The rou tineBCD (for b inary-cod ed d ecimal) converts on e byte of d ata into th reeASCII char acters representing values from 0 (represented as 000) to

    255.

    To do this, BCD perform s a series of divisions on th e byte and on th eremainders of divisions. For example, when it has established howman y hu nd reds ar e in the byte value, it add s 48, the ASCII offset forzero. Take a look at the listing. The d ivision (/ ) and remaind er (/ / )calculations happen before 48 is added. Unlike larger BASICs whichhave a p receden ce of operators (e.g., mu ltiplication is alway s before

    add ition), the Stamp does its math from left to right. You cann ot usepar entheses to alter the ord er, either.

    If you re u nsu re of the ou tcome of a calculation , use th e d ebu g directiveto look at a trial run, like so:

    let BCDin = 200let huns = BCDin/100+48debug huns

    When you d ownload the program to the Stamp, a window will app earon your computer screen showing the value assigned to the variablehu ns (50). If you chan ge the second line to let hu ns = 48+BCDin/ 100,you ll get a very d ifferent r esult (2).

  • 8/7/2019 bs1Appnotes

    18/126

    Page 88 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    BASIC Stamp I Application Notes 4: Controlling and Testing Servos

    By the w ay, you d ont have to use let, but it w ill earn you Brow nie points

    w ith serious comp uter-science types. Most languages oth er than BASICmake a clear distinction between equals as in huns = BCDin/ 100+48and if BCDin = 100 then ...

    Program listing. This program m ay be down loaded from ou r Internetftp site at ftp.parallaxinc.com. The ftp site may be reached directly orthrou gh our w eb site at http :/ / ww w .parallaxinc.com.

    ' PROGRAM: Servo.bas' The Stamp works as a servo test bench. It provides a cycling servo signal' for testing, and measures the pulse width of external servo signals.

    Symbol E = 5 ' Enable pin, 1 = enabledSymbol RS = 4 ' Register select pin, 0 = instructionSymbol char = b0 ' Character sent to LCD.Symbol huns = b3 ' BCD hundredsSymbol tens = b6 ' BCD tens

    Symbol ones = b7 ' BCD onesSymbol BCDin = b8 ' Input to BCD conversion/displayroutine.Symbol buttn = b9 ' Button workspaceSymbol i = b10 ' Index counter

    ' Load text strings into EEPROM at address 0. These will be used to display' status messages on the LCD screen.EEPROM 0,("Cycling... Pulse Width: ")

    ' Set up the Stamp's I/O lines and initialize the LCD.begin: let pins = 0 ' Clear the output lineslet dirs = %01111111 ' One input, 7 outputs.pause 200 ' Wait 200 ms for LCD to reset.

    ' Initialize the LCD in accordance with Hitachi's instructions' for 4-bit interface.i_LCD: let pins = %00000011 ' Set to 8-bit operation.

    pulsout E,1 ' Send above data three timespause 10 ' to initialize LCD.

    pulsout E,1pulsout E,1let pins = %00000010 ' Set to 4-bit operation.pulsout E,1 ' Send above data three times.pulsout E,1pulsout E,1let char = 12 ' Set up LCD in accordance w/

  • 8/7/2019 bs1Appnotes

    19/126

  • 8/7/2019 bs1Appnotes

    20/126

  • 8/7/2019 bs1Appnotes

    21/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 91

    BASIC Stamp I Application Notes

    1

    5: Practical Pulse Measurements

    Introduction. This application note explores several applications for

    the BASIC Stamp's unique pulsin comman d, wh ich m easures theduration of incoming positive or negative pulses in 10-microsecondunits.

    Background. The BASIC Stamp s pulsin comman d measu res the w idthof a pu lse, or the interval between tw o pu lses. Left at that, it might seemto have a limited ran ge of obscur e uses. How ever, pulsin is the key tomany kinds of real-world interfacing using simple, reliable sensors.

    Some possibilities includ e:

    tachometerspeed trapphysics demonstratorcapacitance checkerduty cycle meterlog input analog-to-digital converter

    Pulsin w orks like a stopw atch that keep s time in u nits of 10 microsec-ond s (s). To use it, you m ust sp ecify w hich pin to m onitor, when totrigger on (which implies when to trigger off), and where to put theresulting 16-bit time m easurem ent. The syntax is as follows:

    pulsinpin, trigger condition, variable

    waiting to triggertriggered on

    triggered off

    6924 s

    w3 holds 692 w3 holds 0

    Figure 1. Timing diagram for pulsin 7,0,w3 .

  • 8/7/2019 bs1Appnotes

    22/126

    Page 92 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    BASIC Stamp I Application Notes 5: Practical Pulse Measurements

    Pin is a BASIC Stamp inpu t/ ou tpu t p in (0 to 7). Trigger cond ition is a

    var iable or constant (0 or 1) that sp ecifies the d irection of the tr ansitionthat w ill start the p ulsin timer. If trigger is 0, p ulsin will start measuringw hen a high-to-low transition occur s, because 0 is the ed ges d estina-tion. Variable can be either a byte or w ord variable to hold th e timingmeasurement. In most cases, a word variable is called for, becausepu lsin p rod uces 16-bit results.

    Figure 1 shows h ow pu lsin works. The w aveform represents an inpu t

    at pin 7 that varies between grou nd and +5 volts (V).

    A sm art featu re of pu lsin is its ability to recognize a no-pulse or ou t-of-ran ge cond ition. If the specified transition d oesnt occur w ithin 0.65535second s (s), or if the pu lse to be measu red is longer than 0.65535 s, pulsinw ill give up and retur n a 0 in the variable. This pr events the progr amfrom hanging up wh en theres no inpu t or out-of-range inpu t.

    Lets look at some samp le applications for pu lsin, starting w ith oneinsp ired by the d igital read ou t on an exercise bicycle: pu lsin as atachometer.

    Tachometer. The most obvious w ay to measure the speed of a wheelor shaft in revolutions per minute (rpm) is to count the number of

    Figure 2. Schematic to accompany listing 1,TACH.BAS.

    Q

    Q

    CLK

    D

    1/2 4013

    11

    9

    13

    12

    (ground unusedinputs, pins 8 & 10)

    1k

    +5

    +5

    Hall-effect switchUGN3113U

    orequivalent

    To BASIC Stamppulsin pin

    Magnet onrotatingshaft or disk

  • 8/7/2019 bs1Appnotes

    23/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 93

    BASIC Stamp I Application Notes

    1

    revolutions that occur du ring 1 minu te. The trouble is, the user prob-

    ably w ouldnt want to wait a w hole minute for the answer.

    For a continuously up dated display, we can u se pulsin to m easure th etime the w heel takes to make one comp lete revolution. By d ividing thistime into 60 second s, we get a quick estimate of the rp m. Listing 1 is atachometer pr ogram that w orks just th is way. Figure 2 is the circuit thatprovides input pulses for the program. A pencil-eraser-sized magnetattached to th e wh eel causes a H all-effect sw itch to g enerate a p ulse

    every rotation.

    We could use the H all switch outp ut d irectly, by measu ring the intervalbetween positive pulses, but w e wou ld be m easuring the period of rotation m inus the p ulses. That w ould cause small errors that would bemost significant at high sp eeds. The flip-flop, wired to toggle w ith eachpu lse, eliminates the error by converting the p ulses into a train of squarewaves. Measuring either the high or low interval will give you the

    period of rotation.

    Note th at listing 1 splits the job of d ividing the p eriod into 60 second sinto tw o p arts. This is because 60 second s expressed in 10-s u nits is 6million, which exceeds the ran ge of the Stamps 16-bit calculations. Youw ill see this trick, and others that wor k arou nd the limits of 16-bit math ,throughout the listings.

    Using the flip-flops set/ reset inp uts, this circuit and pr ogram couldeasily be mod ified to create a variety of speed -trap instru men ts. A steelball rolling d ow n a track w ould encounter tw o pairs of contacts to setand reset the flip-flop. Pulsin would measure the interval and comp utethe sp eed for a ph ysics d emonstration (acceleration). More challengingsetups would be required to time baseballs, remote-control cars oraircraft, bullets, or m od el rockets.

    The circuit could also serve as a rudimentary frequency meter. Justdivid e the period into 1 second instead of 1 minu te.

    Duty cycle meter. Many electronic d evices vary th e pow er they d eliverto a load by changing th e du ty cycle of a wav eform; the pr oportion of time that the load is switched fully on to th e time it is fully off. This

    5: Practical Pulse Measurements

  • 8/7/2019 bs1Appnotes

    24/126

    Page 94 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    BASIC Stamp I Application Notes 5: Practical Pulse Measurements

    app roach, found in light dimm ers, pow er supp lies, motor controls and

    amplifiers, is efficient and relatively easy to implement with digitalcomponents. Listing 2 measures the duty cycle of a repetitive pulsetrain by computing the ratio of two pulsin readings and presentingthem as a p ercentage. A reading ap pr oaching 100 percent mean s thatthe inp ut is m ostly on or h igh. The ou tpu t of figur e 2s flip-flop is 50percent. The output of the Hall switch in figure 2 was less than 10percent wh en the device w as monitoring a benchtop d rill pr ess.

    Capacitor checker. The simple circuit in figure 3 charges a capacitor,and then d ischarges it across a resistance when th e button is push ed.This pr oduces a brief pu lse for pu lsin to measu re. Since the timeconstant of the p ulse is determ ined by r esistance (R) times capacitance(C), and R is fixed at 10k, the w idth of the p ulse tells us C. With th eresistance valu es listed , the circuit op erates over a ran ge of .001 to 2.2 F.You may substitute oth er resistors for other ranges of capacitance; just

    be sur e that th e char ging resistor (100k in this case) is about 10 times thevalue of the discharge resistor. This ensures that the voltage at thejun ction of the two r esistors wh en the switch is held dow n is a definitelow (0) inp ut to the Stamp.

    Log-input analog-to-digital converter (ADC). Many sensors haveconvenient linear outputs. If you know that an input of 10 units

    +5

    Cunk

    100k

    10k

    Press totest To BASIC Stamp

    pulsin pin

    Figure 3. Schematic for listing 3,CAP.BAS.

  • 8/7/2019 bs1Appnotes

    25/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 95

    BASIC Stamp I Application Notes

    1

    5: Practical Pulse Measurements

    (degrees, pou nd s, percent hu midity, or whatever) produ ces an outp ut

    of 1 volt, then 20 units w ill prod uce 2 volts. Others, such as therm istors

    and au dio-taper potentiometers, prod uce logarithm ic outp uts. A Radio

    Shack th erm istor (271-110) has a resistance of 18k at 10 C and 12k at20C. N ot linear, and n ot even th e wor st cases!

    While its possible to straighten out a log curve in software, its often

    easier to d eal with it in hard w are. Thats wh ere figur e 4 comes in. Thevoltage-controlled oscillator of the 4046 ph ase-locked loop chip, wh en

    Figure 4. Schematic for listing 4,VCO.BAS.

    Fin

    1/2 4046 To BASIC Stamppulsin pin

    inh5

    1M

    10k0.001F

    Inputvoltage

    outV9 4

    capcap

    6

    7FminFmax

    12

    11

    Input voltage

    0

    250

    500

    750

    1000

    1250

    1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

    Output value

    Figure 5. Log response curve of the VCO.

  • 8/7/2019 bs1Appnotes

    26/126

  • 8/7/2019 bs1Appnotes

    27/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 97

    BASIC Stamp I Application Notes

    1

    ' Transmit data followed by carriage return and linefeed.serout 0,N2400,(#w2," rpm",10,13)pause 1000 ' Wait 1 second between readingsgoto Tach

    ' Listing 3: CAP.BAS' The BASIC Stamp estimates the value of a capacitor by the time required for it to' discharge through a known resistance.

    input 7output 0

    Cap: pulsin 7,1,w1if w1 = 0 then Cap ' If no pulse, try again.if w1 > 6553 then Err ' Avoid overflows.let w1 = w1*10let w1 = w1/14 ' Apply calibration value.if w1 > 999 then uF ' Use uF for larger caps.serout 0,N2400,(#w1," nF",10,13)goto Cap

    uF: let b4 = w1/1000 ' Value left of decimal point.let b6 = w1//1000 ' Value right of decimal point.serout 0,N2400,(#b4,".",#b6," uF",10,13)goto Cap

    ' Listing 2: DUTY.BAS' The BASIC Stamp calculates the duty cycle of a repetitive pulse train.' Pulses in on pin 7; data out via 2400-baud serial on pin 0.

    input 7output 0

    Duty: pulsin 7,1,w2 ' Take positive pulse sample.if w2 > 6553 then Error ' Avoid overflow when w2 is multiplied

    by 10.pulsin 7,0,w3 ' Take negative pulse sample.let w3 = w2+w3let w3 = w3/10 ' Distribute multiplication by 10 into twolet w2 = w2*10 ' parts to avoid an overflow.let w2 = w2/w3 ' Calculate percentage.serout 0,N2400,(#w2," percent",10,13)pause 1000 ' Update once a second.goto Duty

    ' Handle overflows by skipping calculations and telling the user.Error: serout 0,N2400,("Out of range",10,13)

    pause 1000goto Duty

    5: Practical Pulse Measurements

  • 8/7/2019 bs1Appnotes

    28/126

    BASIC St I A li ti N t

  • 8/7/2019 bs1Appnotes

    29/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 99

    BASIC Stamp I Application Notes

    1

    6: A Serial Stepper Controller

    Introduction. This application note demonstrates simple hardware

    and software techn iques for driving and controlling comm on four-coilstepper motors.

    Background. Stepper motors translate digital switching sequencesinto motion. They are used in p rinters, automated machine tools, disk dr ives, and a variety of other app lications requ iring pr ecise motionsun der compu ter control.

    Unlike ord inary dc motors, which spin freely wh en pow er is applied,steppers require that their power source be continuously pulsed inspecific patterns. These patterns, or step sequences, determine thespeed an d d irection of a steppers motion. For each p ulse or step inpu t,the stepp er m otor rotates a fixed an gular increment; typically 1.8 or 7.5degrees.

    The fixed stepp ing ang le gives stepp ers their p recision. As long as themotors maximum limits of speed or torque are not exceeded, thecontrolling pr ogram know s a steppers precise position at an y giventime.

    Steppers are driven by the interaction (attraction and repulsion) of magnetic fields. The driving magnetic field rotates as strategicallyplaced coils are switched on an d off. This pu shes and p ulls at perma-nent magnets arranged around the edge of a rotor that drives the output

    Figure 1. Schematic for the serial stepper controller.

    PIC1 6 C5 6

    01234567

    +5V Vi n

    GNDBASIC STAMP

    EEPROM

    (C) 1992 Parallax, Inc.

    PC

    ULN 2003TO PIN 11

    TO PIN 10

    TO PIN 1

    TO PIN 4

    NCNC

    1k

    1k 1k

    1k

    BLKBRN

    YELORG

    GRN

    RED

    +5

    +12

    Stepper Motor

    NC

    1

    8

    16

    9

    IN 1

    IN 2

    IN 3

    IN 4

    IN 5

    IN 6

    IN 7GND

    OUT 1

    OUT 2

    OUT 3

    OUT 4

    OUT 5

    OUT 6

    OUT 7TESTSerial Input

    22k

    +5

    AIRPAX COLOR CODE:RED & GREEN = COMMON

    Serial Output

    BASIC Stamp I Application Notes 6 A S i l S C ll

  • 8/7/2019 bs1Appnotes

    30/126

    Page 100 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    BASIC Stamp I Application Notes 6: A Serial Stepper Controller

    shaft. When the on-off pattern of the m agnetic fields is in th e prop ersequence, the stepp er tur ns (wh en its not, the stepp er sits and qu ivers).

    The most comm on stepp er is the four-coil un ipolar variety. These arecalled u nipolar because they requ ire only that th eir coils be dr iven onand off. Bipolar stepp ers require th at the p olarity of power to the coilsbe reversed.

    The normal stepp ing sequence for four-coil un ipolar steppers ap pearsin figure 2. There are other, special-pu rp ose stepping sequences, suchas half-step and wave d rive, and ways to d rive steppers w ith mu lti-phase analog waveforms, but this application concentrates on thenormal sequence. After all, its the sequence for which all of theman ufacturers specifications for torqu e, step an gle, and speed app ly.

    If you r un the stepp ing sequence in figure 2 forw ard , the stepp er rotatesclockwise; ru n it backwar d, and the stepp er rotates counterclockw ise.The motors speed d epends on how fast the controller run s through thestep sequ ence. At an y time th e controller can stop in m id sequ ence. If itleaves power to any p air of energized coils on, the motor is locked inplace by their m agnetic fields. This points ou t another step per m otorbenefit: bu ilt-in brak es.

    Many m icrop rocessor stepper d rivers use four ou tpu t bits to generatethe stepp ing sequence. Each bit drives a pow er transistor that sw itcheson the appropriate stepper coil. The stepping sequence is stored in alookup table and read ou t to the bits as required.

    This design takes a slightly different ap pr oach. First, it uses only tw ooutp ut bits, exploiting th e fact that the states of coils 1 and 4 are always

    1 2 3 4 1

    coil 1 1 1 0 0 1coil 2 0 0 1 1 0coil 3 1 0 0 1 1coil 4 0 1 1 0 0

    Step Sequence

    Figure 2. Normal stepping sequence.

    BASIC Stamp I Application Notes6 A S i l St C t ll

  • 8/7/2019 bs1Appnotes

    31/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 101

    BASIC Stamp I Application Notes

    1

    6: A Serial Stepper Controller

    the inv erse of coils 2 and 3. Look at figur e 2 again. Whenev er coil 2 getsa 1, coil 1 gets a 0, and the sam e hold s for coils 3 and 4. In Stam p d esigns,outp ut bits are too precious to w aste as simp le inverters, so we give thatjob to tw o sections of the ULN2003 inverter/ d river.

    The second difference between th is and oth er stepper d river designs isthat it calculates the stepp ing sequence, rather than r eading it ou t of atable. While its very easy to create tab les with th e Stam p, the calcula-tions required to create the two-bit sequence required are very simp le.And reversing the motor is easier, since it requires only a singleadd itional pr ogram step. See the listing.

    How it works. The stepp er controller accepts comm and s from a termi-nal or PC via a 2400-baud serial connection. When p ower is first ap pliedto the Stamp , it send s a prom pt to be displayed on the terminal screen.The user typ es a string repr esenting the d irection (+ for forw ard , forbackward ), nu mber of steps, and step d elay (in m illisecond s), like this:

    step>+500 20

    As soon as the u ser presses enter, retur n, or any n on-nu merical charac-ter at the end of the line, the Stamp starts the motor ru nning . When thestepp ing sequence is over, the Stamp sends a n ew step> p romp t to theterminal. The sample command above would take about 10 seconds(500 x 20 millisecond s). Comm and s entered before the prom pt r eap-pears are ignored.

    On the hard ware side, the application accepts any stepp er that d raws500 mA or less per coil. The schematic shows the color code for anAirpax-brand step per, but there is no stand ard ization amon g different

    YELLOW

    ORANGE

    RED

    BROWN

    BLACK

    GREEN

    Figure 3. Color code for Airpax steppers.

  • 8/7/2019 bs1Appnotes

    32/126

    BASIC Stamp I Application Notes7: Using a Thermistor

  • 8/7/2019 bs1Appnotes

    33/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 103

    BASIC Stamp I Application Notes

    1

    7: Using a Thermistor

    Introduction. This app lication n ote shows how to measure temp era-ture using an inexpensive thermistor and the BASIC Stamps potcomman d . It also discusses a techniqu e for correcting n onlinear d ata.

    Background. Radio Shack offers an inexpensive and relatively precisethermistora component whose resistance varies with temperature.The BASIC Stamp has th e bu ilt-in ability to m easure r esistance with thepot comm and and an external capacitor. Put th em together, and yourStamp can measure the temp eratur e, right? Not withou t a little math.

    The therm istors resistance d ecreases as the tem peratu re increases, butthis respon se is not linear. There is a table on th e back of the therm istorpackage that lists the resistance at various temperatures in degreescelsius (C). For th e sake of brevity, we w ont rep rod uce that table here,but the lefthand graph of figure 1 shows the general shape of thethermistor response curve in terms of the more familiar Fahrenheitscale (F).

    The pot comm and throws u s a curve of its own, as shown in figure 1(right). Thou gh not as p ronou nced as the therm istor cur ve, it must befigu red into ou r temp eratur e calculations in ord er for the results to beusable.

    One p ossibility for correcting the combined curves of the therm istorand pot command would be to create a lookup table in the StampsEEPROM. The table w ould have to be qu ite large to cover a r easonabletemp eratur e range at 1 pr ecision. An alternative wou ld be to create asmaller table at 10 pr ecision, and figur e wh ere a p articular r eading

    Figure 1. Response curves of the thermistor andpot command.

    0

    1020

    30

    40

    5060

    0 50 100 150Temperature F

    Thermistor (k)

    0

    50

    100

    150

    200

    250

    0 10 20 30 40 50Input resistance (k )

    Pot command output

  • 8/7/2019 bs1Appnotes

    34/126

  • 8/7/2019 bs1Appnotes

    35/126

    BASIC Stamp I Application Notes 7: Using a Thermistor

  • 8/7/2019 bs1Appnotes

    36/126

    Page 106 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    p pp

    The solution is to factor the coefficients an d rearrang e them into sm allerpr oblems that can be solved w ithin the limit. For examp le (using PV tostand for Pot Val):

    g

    The program in the listing is an example of just such factoring andrearran gement. Remem ber to watch ou t for the lower limit as well. Tryto keep intermediate results as high as possible within the Stampsinteger limits. This will redu ce the effect of tru ncation errors (w here an yvalue to th e right of the d ecimal point is lost).

    Conclusion. The finished p rogram, wh ich r eports the temperature tothe PC screen via the debug comm and , is deceptively simp le.An informalcheck of its outp ut found that it tracks within 1 F of a mercury/ glass bulbtherm ometer in the ran ge of 60 F to 90 F. Ad ditional range could beobtained at the expense of a third-order equation; however, currentperform ance is more than ad equate for use in a hou sehold therm ostat orother n oncritical application. Cost and complexity are far less than thatof a linear sensor, precision voltage reference, and analog-to-digitalconverter.

    If you adap t this app lication for your ow n u se, comp onent tolerances willpr obably prod uce different results. How ever, you can calibrate the pr o-gram very easily. Connect the therm istor and a stable, close-tolerance 0.1-F capacitor to the Stamp as shown in figure 2. Run the pr ogram an d notethe value that appears in the debug wind ow. Compare it to a knownaccur ate therm ometer located close to the therm istor. If the therm ometersays 75 and the Stamp 78, redu ce the value of C0 by 3. If the therm ometersays 80 and the Stamp 75, increase the value of C0 by 5. This works becausethe relationship between the th ermistor resistance and the temp erature isthe sam e, only the value of the capacitor is d ifferent. Adjusting C0 correctsthis offset.

    Program listing. These programs m ay be d ownloaded from our Internet ftpsite at ftp.par allaxinc.com. The ftp site may be reached d irectly or thr oughour w eb site at http:/ / ww w.par allaxinc.com.

    PV*PV*3 PV*PV*3 PV PV*31250 5*5*5*5*2 25 50= = *

  • 8/7/2019 bs1Appnotes

    37/126

  • 8/7/2019 bs1Appnotes

    38/126

  • 8/7/2019 bs1Appnotes

    39/126

    BASIC Stamp I Application Notes 8: Sending Morse Code

  • 8/7/2019 bs1Appnotes

    40/126

    Page 110 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    The table on the next page shows the encoding scheme used in thispr ogram . A single byte represents a Morse character. The h ighest fivebits of the byte represent th e actual dots(0s) and dash es (1s), wh ile thelower th ree bits represent the nu mber of elements in the character. Forexample, the letter F is dot dot dash dot, so it is encoded 0010x100,w here x is a don t-care bit. Since Morse characters can contain u p to sixelements, w e have to h and le the exceptions. Fortu nately, we have som eexcess capacity in the n um ber-of-elements p ortion of the b yte, whichcan represent n um bers up to seven. So w e assign a six-element charac-ter end ing in a dot th e num ber six, while a six-element character end ingin a dash gets the num ber seven.

    The program listing shows how these bytes can be played back toproduce Morse code. The table of symbols at the beginning of thepr ogram contain the timing d ata for the dots and dash es themselves. If you w ant to change the program s sending speed, just enter new valuesfor dit_length , dah_length , etc. Make sure to keep the timing

    Char Morse Binar y DecimalA 01000010 66B 10000100 132C 10100100 164D 10000011 131

    E 00000001 1F 00100100 36G 11000011 195H 00000100 4I 00000010 2J 01110100 116K 10100011 163L 01000100 68M 11000010 194N 10000010 130O 11100011 227P 01100100 100Q 11010100 212R 01000011 67

    S 00000011 3T 10000001 129U 00100011 35V 00010100 20

    W 01100011 99X 10010100 148Y 10110100 180Z 11000100 1960 11111101 2531 01111101 1252 00111101 613 00011101 294 00001101 135 00000101 56 10000101 1337 11000101 1978 11100101 2299 11110101 245

    Char Morse Binary Decimal

    Morse Characters and their Encoded Equivalents

    BASIC Stamp I Application Notes8: Sending Morse Code

  • 8/7/2019 bs1Appnotes

    41/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 111

    1

    relationships rou ghly the same; a dash shou ld be about three times aslong as a dot.

    The program uses the BASIC Stamps lookup function to play se-qu ences of Morse characters. Lookup is a particularly mod ern featureof Stam p BASIC in that it is an object-oriented data stru cture. It not on lycontains the data, it also know s how to retrieve it.

    Modifications. The program could readily be modified to transmitmessages whenever the Stamp detects particular conditions, such asBATTERY LOW. With som e ad ditional pr ogram ming and analog-to-digital hard war e, it could serve as a low-rate telemetry u nit readab le byeither automated or manu al means.

    Program listing. This program m ay be down loaded from ou r Internetftp site at ftp.parallaxinc.com. The ftp site may be reached directly orthrou gh ou r web site at http:/ / ww w .parallaxinc.com.

    ' Program MORSE.BAS' This program sends a short message in Morse code every' minute. Between transmissions, the Stamp goes to sleep' to conserve battery power.Symbol Tone = 100Symbol Quiet = 0Symbol Dit_length = 7 ' Change these constants toSymbol Dah_length = 21 ' change speed. Maintain ratiosSymbol Wrd_length = 42 ' 3:1 (dah:dit) and 7:1 (wrd:dit).Symbol Character = b0Symbol Index1 = b6Symbol Index2 = b2Symbol Elements = b4

    Identify:output 0: output 1for Index1 = 0 to 7' Send the word "PARALLAX" in Morse:

    lookup Index1,(100,66,67,66,68,68,66,148),Charactergosub Morse

    nextsleep 60goto Identify

    Morse:

    BASIC Stamp I Application Notes 8: Sending Morse Code

  • 8/7/2019 bs1Appnotes

    42/126

    Page 112 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    let Elements = Character & %00000111if Elements = 7 then Adjust1

    if Elements = 6 then Adjust2Bang_Key:for Index2 = 1 to Elements

    if Character >= 128 then Dahgoto Dit

    Reenter:let Character = Character * 2

    nextgosub char_spreturn

    Adjust1:Elements = 6goto Bang_Key

    Adjust2:Character = Character & %11111011goto Bang_Keyend

    Dit:

    high 0sound 1,(Tone,Dit_length)low 0sound 1,(Quiet,Dit_length)goto Reenter

    Dah:high 0sound 1,(Tone,Dah_length)low 0

    sound 1,(Quiet,Dit_length)goto Reenter

    Char_sp:sound 1,(Quiet,Dah_length)return

    Word_sp:sound 1,(Quiet,Wrd_length)return

    BASIC Stamp I Application Notes9: Constructing a Dice Game

  • 8/7/2019 bs1Appnotes

    43/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 113

    1

    Introduction. This app lication note d escribes an electronic dice gam ebased on the BASIC Stamp . It show s how to connect LED displays to theStamp, and how to mu ltiplex inputs and outpu ts on a single Stamp pin.

    Background. Much of BASICs su ccess as a p rogram ming langua ge ispr obably the result of its w idespread use to prog ram g ames. After all,games are just simu lations that hap pen to be fun.

    How it works. The circuit for the d ice game u ses Stamp pins 0 throu gh6 to source cur rent to th e anod es of two sets of seven LEDs. Pin 7 andthe switching transistors determine which set of LEDs is grounded.Whenever th e lefthand LEDs are on, the r ight are off, and vice versa.To light u p the LEDs, the Stamp pu ts die1s pattern on p ins 0-6, andenables die1 by making p in 7 high. After a few millisecond s, it p utsdie2s pattern on p ins 0-6 and takes pin 7 low to enable die2.

    In add ition to sw itching betw een the dice, pin 7 also serves as an inpu tfor the press-to-roll pushbutton. The program changes the pin to aninpu t and checks its state. If the switch is up, a low app ears on pin 7because the base-emitter jun ction of the transistor pu lls it dow n to abou t0.7 volts. If the switch is pressed, a h igh ap pears on pin 7. The 1k resistorpu ts a high on p in 7 when it is an inpu t, but pin 7 is still able to pu ll thebase of the transistor low w hen it is an outp ut. As a result, holding theswitch d ow n d oesnt affect the Stamp s ability to d rive the d isplay.

    PIC 1 6 C 5 6

    01234567

    +5V Vin

    GNDBASIC STAMP

    EEPROM

    (C) 1992 Parallax, Inc.

    PC

    2N2222

    47k

    +5

    1k

    1k

    2N2222

    Roll

    Green LEDs arranged in pip pattern with cathodes ()connected together, anodes (+) to Stamp pins as shown.

    1k (all)

    1k

    0 1

    5 2

    4 3

    6

    0 1

    5 2

    4 3

    6

    Schematic to accompany program DICE.BAS.

  • 8/7/2019 bs1Appnotes

    44/126

    BASIC Stamp I Application Notes10: Humidity and Temperature

  • 8/7/2019 bs1Appnotes

    45/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 115

    1

    Introduction. This application note show s how to interface an inexpen-sive hu mid ity/ temperatu re sensor kit to the Stamp .

    Background. When its hot, high hu mid ity makes it seem h otter. Whenits cold, low hu mid ity makes it seem colder. In ar eas wh ere electroniccomponents are handled, low humidity increases the risk of electro-static discharge (ESD) and dam age. The relationship betw een temp era-tur e and hu mid ity is a good ind ication of the efficiency of heavy-du tyair-cond itioning equ ipmen t that u ses evap orative cooling.

    Despite the value of knowing tem peratu re and h um idity, it can be hardto find suitable hum idity sensors. This app lication solves that p roblemby borrowing a sensor kit manufactured for compu terized hom e weatherstations.

    The kit, available from the sou rce listed at the end of this app licationnote for $25, consists of fewer than a d ozen comp onents an d a sm all (0.5"x 2.75") pr inted circuit board . Assembly entails soldering th e comp o-nents to the board . When its don e, you h ave two sensors: a temp era-ture-dependent current source and a h um idity-dependent oscillator.

    Once the sensor board is comp lete, connect it to the Stamp using th ecircuit shown in the figur e and d own load the software in the listing. The

    Schematic to accompany program HUMID.BAS.

    220

    2 7

    4024counter(128)

    13

    14

    +50.1 F

    4 (RH clock output)

    1 (Temp )

    2 (Temp +)

    5 (RH clock enable)

    6

    +5

    3

    Humidity/TemperatureBoard

    0

    1

    23

    BASICStamp I/O

    pins

    4024counter(128)

    BASIC Stamp I Application Notes 10: Humidity and Temperature

  • 8/7/2019 bs1Appnotes

    46/126

    Page 116 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    debug wind ow w ill appear on you r PC screen showing values repre-senting hu mid ity and tem peratu re. To get a feel for the board s sensi-tivity, try this: Breathe on th e sensor board and watch th e debug valueschange. The humidity value should increase dramatically, while thetemperature n um ber (which decreases as the temperature goes up ) willfall a few coun ts.

    How it works. The largest portion of the program is devoted tomeasu ring the temp erature, so well start there. The temp erature sensoris an LM334Z constant-current source. Current through the devicevaries at the rate of 0.1A per 1 C chang e in temp eratur e. The progr amin the listing passes curr ent from p in 2 of the Stamp throu gh th e sensorto a capacitor for a short period of time, starting w ith 5000 s. It thenchecks the cap acitors state of charge th rou gh p in 1. If the capacitor isnot charged enou gh for p in 1 to see a logical 1, the Stamp d ischarges th ecapacitor an d tries again, with a slightly w ider p ulse of 5010 s.

    It stays in a loop, charging, checking, d ischarging, an d increasing thecharging p ulse un til the capacitor show s as a 1 on p in 1s inpu t. Since therate of charge is prop ortional to cur rent, and th e cur rent is prop ortionalto temperature, the width of the pulse that charges the capacitor is arelative ind ication of temp eratur e.

    Sensing hu mid ity is easier, thanks to th e design of the kits hard w are.The hum idity sensor is a capacitor wh ose value chang es with relativehu mid ity (RH). At a relative hu mid ity of 43 percent and a temp eratur eof 77 F, the sensor has a v alue of 122 pF 15 percent. Its value chan gesat a r ate of 0.4 pF 0.05 pF for each 1-percent change in RH .

    The sensor con trols the p eriod o f a 555 timer w ired as a clock oscillator.The clock period var ies from 225 s at an arid 10-per cent RH to 295 sat a m ugg y 90-percent RH . Since w ere m easuring th is chang e with theStamps pulsin comman d, w hich has a resolution of 10 s, we need toexaggerate those chan ges in period in ord er to get a usable chan ge inoutp ut v alue. Thats the p ur pose of the 4024 counter.

    We norm ally think of a coun ter as a frequency d ivider, but by d efinitionits also a p eriod m ultiplier. By d ividing th e clock outp ut by 128, wecreate a square w ave with a p eriod 128 times as long. Now hu mid ity is

  • 8/7/2019 bs1Appnotes

    47/126

    BASIC Stamp I Application Notes 10: Humidity and Temperature

  • 8/7/2019 bs1Appnotes

    48/126

    Page 118 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    low 2: low 3let temp = 500 ' Start temp at a reasonable value.

    ReadTemp:output 1: low 1pause 1 ' Discharge the capacitor.input 1 ' Get ready for input.pulsout 2,temp ' Charge cap thru temp sensor.if pin1 = 1 then ReadRH ' Charged: were done.let temp = temp + 1 ' Else try againgoto ReadTemp ' with wider pulse.

    ReadRH:high 3 ' Turn on the 555 timerpause 500 ' and let it stabilize.pulsin 0,1,RH ' Read the pulse width.low 3 ' Kill the timer.debug temp:debug RH ' Display the results.goto Loop ' Do it all again.

    BASIC Stamp I Application Notes11: Infrared Communication

  • 8/7/2019 bs1Appnotes

    49/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 119

    1

    Introduction. This application note shows how to build a simple andinexpensive infrared commu nication interface for th e BASIC Stamp .

    Background. Todays hottest products all seem to have one thing incommon ; w ireless comm un ication. Personal organizers beam d ata intodesktop compu ters and w ireless remotes allow us to channel surf fromour couches. Not wanting the BASIC Stamp to be left behind, wedevised a simp le infrared data link. With a few inexpensive par ts fromyour neighborhood electronics store you can communicate at 1200baud over distances greater than 10 feet indoors. The circuit can bemod ified for greater range by th e use of a higher p erformance LED.

    How it works. As the name implies, infrared (IR) remote controlstransm it instructions over a beam of IR light. To avoid interference fromother h ousehold sources of infrared , primarily incandescent lights, thebeam is mod ulated w ith a 40-kHz carrier. Legend has it that 40 kH z wasselected because the p revious generation of ultrasonic remotes work ed

    Schematic to accompany program IR.BAS.

    4.7k

    PC RS-232output

    pin 4 of555 timer

    GP1U52Xoutput

    PC RS-232input

    CMOS inverter(1/6 74HCT04)

    PC Interfaces

    Transmit Receive

    +5

    Trigger GND

    Output

    TLC555

    1

    Threshold

    Discharge

    Reset

    Control VDD

    85

    4

    RB10k

    CT0.001F

    1k

    7

    6

    2

    3

    100

    2N2222

    IR LEDSerial inputto 1200 bps

    GP1U52X

    +5321

    4.7k

    +5

    Serialoutput

    10 feetor moreindoors

    10k

    10k potRA

    1N914

  • 8/7/2019 bs1Appnotes

    50/126

  • 8/7/2019 bs1Appnotes

    51/126

  • 8/7/2019 bs1Appnotes

    52/126

  • 8/7/2019 bs1Appnotes

    53/126

  • 8/7/2019 bs1Appnotes

    54/126

  • 8/7/2019 bs1Appnotes

    55/126

    BASIC Stamp I Application Notes

    H i k I fi 1 h TLC555 i i d ill

    12: Sonar Rangefinding

  • 8/7/2019 bs1Appnotes

    56/126

    Page 126 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    How it works. In figur e 1, the TLC555 timer is connected as a oscillator;officially an astable multivibrator . When its reset pin is high , the circuit

    sends a 40-kHz signal to the u ltrasonic transmitter, which is really justa specialized sor t of speaker . When reset is low , the 555 is silenced.

    In the receiving section, the ultrasonic receivera high-frequencymicroph onefeeds th e CA5160 op am p, w hich am plifies its signal 100times. This signal goes to an N E567 tone decod er, wh ich looks for a closematch between the frequency of an incoming signal and that of itsinternal oscillator. When it finds on e, it p ulls its outpu t pin low.

    Figur e 2 illustrates the son ar r anging pr ocess. The Stamp activates the555 to send a brief 40-kH z p ulse out throu gh th e ultrasonic transmitter.Since the receiver is an inch aw ay, it hears this initial pulse loud andclear, starting abou t 74 s after the p ulse begins (the time requ ired forsound to trav el 1 inch at 1130 feet per second ). After the 567 has h eardenou gh of th is pu lse to recognize it as a valid 40-kHz signal, it pu lls itsoutput low.

    After pulsout finishes, the transmitter continues to r ing for a shorttime. The pu rp ose of the felt or cloth w rap ping on the transm itter is todam p ou t this ringing as soon as possible. Meanw hile, the Stamp hasissued th e pulsin comman d an d is w aiting for the 567 outpu t to gohigh to begin its timing p eriod. Than ks to the time required for the endof the pu lse to reach th e receiver, and the p ulse-stretching tend ency of the 567 outp ut filter, the Stamp has p lenty of time to catch the rising

    edge of th e 567 outp ut.

    Thats why we have to damp the ringing of the transmitter. If thetransmitter were allowed to ring undamped, it would extend theinterval between the end of pulsout and the beginning of pulsin ,reducing the minimum range of the sonar. Also, if the ringing wereallowed to grad ually fade away, the outp ut of the 567 might chatterbetween low an d h igh a few tim es before settling high. This wou ld fool

    pulsin into a false, low r eading.

    On the other hand, if we prevented the receiver from hearing thetransm itter at all, pulsin wou ld not get a positive edg e to trigger on.It would time out and return a reading of 0.

  • 8/7/2019 bs1Appnotes

    57/126

    BASIC Stamp I Application Notes

    Make the transmitter louder Most ultrasonic transmitters can with

    12: Sonar Rangefinding

  • 8/7/2019 bs1Appnotes

    58/126

    Page 128 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    Make the transmitter louder. Most ultrasonic transmitters can with-stand inpu ts of 20 or more volts peak-to-peak; our s uses only 5.

    Tinker with the tone decoder, especially the loop and output filtercapacitors. These are critical to reliable detection and ranging. Wearrived at the values used in the circuit by calculating reasonablestarting p oints, and then su bstituting like mad. Theres pr obably stillsome room for improvement.

    Many ultrasonic transducers can work as both a speaker and micro-

    ph one. Devise a way to mu ltiplex the transm it and r eceive fun ctions toa single transd ucer. This w ould simplify th e use of a r eflector or baffle.

    Parts sources. Suitable ultrasonic transd ucers are av ailable from A llElectronics, 1-800-826-5432. Part no. UST-23 includes both transmitterand receiver. Price was $2 at the time of this wr iting. Marlin P. Jones an dAssociates, 1-800-652-6733, stock #4726-UT. Price was $3.95 at th e tim eof this writing. Hosfelt Electronics, 1-800-524-6464, carries a slightly

    more sensitive p air of transd ucers as par t no. 13-334. Price was $3.50 atthe time of this writing.

    Program listing. This program m ay be down loaded from ou r Internetftp site at ftp.parallaxinc.com. The ftp site may be reached directly orthrou gh our w eb site at http :/ / ww w.par allaxinc.com.

    ' Program: SONAR.BAS' The Stamp runs a sonar transceiver to measure distances' up to 12 feet.

    Symbol echo_time = w2 ' Variable to hold delay time

    setup: let pins = 0 ' All pins lowoutput 0 ' Controls sonar xmitterinput 1 ' Listens to sonar receiver

    ping: pulsout 0,50 ' Send a 0.5-ms pingpulsin 1,1,echo_time ' Listen for returndebug echo_time ' Display time measurementpause 500 ' Wait 1/2 secondgoto ping ' Do it again.

  • 8/7/2019 bs1Appnotes

    59/126

  • 8/7/2019 bs1Appnotes

    60/126

  • 8/7/2019 bs1Appnotes

    61/126

  • 8/7/2019 bs1Appnotes

    62/126

  • 8/7/2019 bs1Appnotes

    63/126

  • 8/7/2019 bs1Appnotes

    64/126

  • 8/7/2019 bs1Appnotes

    65/126

  • 8/7/2019 bs1Appnotes

    66/126

  • 8/7/2019 bs1Appnotes

    67/126

  • 8/7/2019 bs1Appnotes

    68/126

  • 8/7/2019 bs1Appnotes

    69/126

    BASIC Stamp I Application Notes

  • 8/7/2019 bs1Appnotes

    70/126

    Page 140 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

  • 8/7/2019 bs1Appnotes

    71/126

  • 8/7/2019 bs1Appnotes

    72/126

  • 8/7/2019 bs1Appnotes

    73/126

  • 8/7/2019 bs1Appnotes

    74/126

  • 8/7/2019 bs1Appnotes

    75/126

  • 8/7/2019 bs1Appnotes

    76/126

  • 8/7/2019 bs1Appnotes

    77/126

  • 8/7/2019 bs1Appnotes

    78/126

    BASIC Stamp I Application Notes17: Solar-Powered Stamp

    Introduction. This application note show s how to operate the Stamp 24hou rs a d ay from the p ower pr ovided by a 1.5" x 2.5" solar battery. Theexample application takes outdoor temperature measurements every12 d h l h i d i i f d li k

  • 8/7/2019 bs1Appnotes

    79/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 149

    1

    12 second s, then r elays them to a compu ter indoor s via an infrared link.

    Background. A stand ard 9-volt battery can p ower th e Stamp for a longtime with the u se of the sleep and nap comman d s. But eventu ally thebattery will die, if only from old age.

    Althoug h its usu ally no p roblem to just replace the battery, there areapp lications that require long periods of unattend ed op eration. Imag-ine a mou ntaintop w eather station, forest wildlife counter, or floatingsensor buoy , drifting in th e currents at sea. Now imagine the cost of mou nting an exped ition to rep lace the Stamp s battery. Whew !

    There are also less exotic places in w hich ind epend ence from batterieswou ld be a good idea. How about p ollution-measuring instrum ents atthe top of a p ole, or an electronic bicycle speed ometer?

    Schematic to accompany program SOLAR.BAS

    PCRS-232input

    CMOS inverter(1/6 74HCT04)

    TriggerGND

    Output

    TLC555

    1

    Threshold

    Discharge

    Reset

    Control VDD

    85

    4

    10k

    0.001F

    1k76

    2

    3

    220

    2N2222

    IR LED

    Stamppin 2 +5

    321

    4.7k

    +5

    10k

    5k pot(adjust for

    40kHz)

    0.1F

    10kthermistor(RadioShack271-110)

    Stamppin 0

    Stamppin 1

    High-efficiency solar cell(Edmund G52,169)

    RED

    BLK

    Stamp+9V

    1-Farad, 5.5 V Super Cap(Digi-Key P6955)

    Stamp+5V

    GP1U52X(RadioShack

    276-137)

  • 8/7/2019 bs1Appnotes

    80/126

  • 8/7/2019 bs1Appnotes

    81/126

  • 8/7/2019 bs1Appnotes

    82/126

  • 8/7/2019 bs1Appnotes

    83/126

  • 8/7/2019 bs1Appnotes

    84/126

    BASIC Stamp I Application Notes18: One Pin, Many Switches

    Introduction. This app lication note show s how to read mu ltiple switchesthrough a single inpu t/ outp ut (I/ O) pin by using the pot command.

    Background. If your BASIC Stamp application needs to check the

  • 8/7/2019 bs1Appnotes

    85/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 155

    1

    status of more than a few sw itches, you have pr obably considered usingexternal hardware to do the job. The trouble is that most hardwaresolutions still use m ore than on e I/ O pin, and often requ ire consider-able program overhead.

    Now, consider the pot command. It reads a resistance and returns aproportional number. What if you wired your switches to vary theresistance m easured by pot ? With an app rop riate lookup r outine, youdbe able to determine w hich switch w as pressed.

    Thats exactly the method w ere going to d emon strate here.

    How it works. As the figure show s, we w ired up eight switches andeight 1k resistors in a sort of pushbutton-pot arrangement. When noswitch is p ressed , the circuits resistance is the su m of all of the resistor sin series; 8k. If you press the switch closest to the pot pin (S0), thenetw ork is shor ted out, so th e resistance is 0. Press S1, and the resistanceis 1k. And so on.

    To see this effect in action, follow these step s: Wire up the circuit in thefigu re, connect the Stamp to y our PC, run STAMP .EXE , and pr ess ALT-P(calibrate pot). Select the ap pr op riate I/ O pin ; in this case pin 0. The PCscreen w ill display a dialog box show ing a suggested v alue for the potscale factorthe number that ensures a full-scale response for theconnected combination of the resistor(s) and capacitor.

    Schematic to accompany program MANY_ SW.BAS

    1k 1k 1k 1k 1k 1k 1k 1k

    S0 S1 S2 S3 S4 S5 S6 S7

    0.1 F

    Stamp pin 0

  • 8/7/2019 bs1Appnotes

    86/126

  • 8/7/2019 bs1Appnotes

    87/126

  • 8/7/2019 bs1Appnotes

    88/126

  • 8/7/2019 bs1Appnotes

    89/126

  • 8/7/2019 bs1Appnotes

    90/126

  • 8/7/2019 bs1Appnotes

    91/126

    BASIC Stamp I Application Notes 19: Using Button Effectively

    So as long as the bu tton is not pressed, the button comm and will skipover the code that p lays the selected tu ne. When the button is pressed,the tun e will play.

    This button comm and d oesnt require deboun ce or autorep eat, because

  • 8/7/2019 bs1Appnotes

    92/126

    Page 162 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    q pthe tu nes are relatively long. By the tim e a tu ne is finished playing, theuser h as probably already released th e button. If he hasn t, the tune w illsimply play again without delay.

    The second button command is:

    button 6,0,200,60,b1,1,Pick

    This translates to: Read the bu tton on pin 6. When it is pressed, therew ill be a logical 0 on the p in. Debounce the sw itch and d elay 200 cyclesthrough this command before starting autorepeat. Once autorepeatbegins, delay 60 cycles throu gh b utton between r epeats. Use b1 as aw orkspace. When the bu tton is pressed (1) go to the label Pick .

    From th e users stand point, this mean s that a single pr ess of the selectbutton lights the next LED in the sequence. H olding d own the buttonmakes th e LEDs scan rap idly. Releasing the sw itch causes th e currentlylit LED to rem ain on.

    Its hard to describe what an important difference debounce andautor epeat mak e in the ease and qu ality of a user interface. The best wayis to offer a comp arison. Listing 2 is the same jukebox prog ram as listing1, but w ithout the bu tton comman d to d eboun ce the switches. It usesthe same circuit as listing 1, so you can alternately dow nload the tw oprogram s for an instant comparison.

    When you run NO _BTN .BAS, youll find no d ifference in the op eration of the play button. Remember that buttons debounce and autorepeatfeatures were turn ed off in the original progr am any wa y. If you n eed toeconom ize on variables, you can substitute a simp le if/then for button incases that d ont use these features.

    The select button is a different story. It becomes almost impossible toselect the LED you wan t. To mak e the compar ison fair, we even ad ded

    BASIC Stamp I Application Notes

    a brief pau se to the Pick rou tine as a sort of deboun cing. It helps, but notenou gh to m ake the bu tton action feel solid and pr edictable. This is thekind of case that requ ires button .

    Program listing. These programs m ay be down loaded from our Internet

    19: Using Button Effectively

  • 8/7/2019 bs1Appnotes

    93/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 163

    1

    ftp site at ftp.parallaxinc.com. The ftp site may be reached directly orthrou gh ou r web site at http:/ / ww w .parallaxinc.com.

    Listing 1: BTN_JUKE.BAS (Demonstration of the Button command)

    ' The Stamp serves as a tiny jukebox, allowing you to pick from one of' five musical (?) selections created with the sound command. The point' of the program is to demonstrate the proper way to use the button' command. The juke has two buttons--one that lets you pick the tune' by "scrolling" through five LEDs, and the other that plays the tune' you selected. The selection button uses the debounce and autorepeat' features of button, while the play button is set up for immediate' response without delay or autorepeat.

    SYMBOL Select = b2 ' Variable to hold tune selection, 0-4.

    let dirs = %00111111 ' Pins 6 & 7 are inputs for buttons.let w0 = 0 ' Initialize all variables to zerolet w1 = 0 ' (includes clearing the button variables b0,b1)let pins = %00000010 ' Turn on the first selection LED.

    ' The main program loop. Main scans the two buttons and branches to' no_play or Pick, depending on which button was pressed. Note the two' different ways the button command is used. In the first case,' button skips over the branch instruction that jumps to the' appropriate tune routine _unless_ the button is pushed.' The tunes are fairly long, so no debounce is needed, and' autorepeat isn't appropriate (the next trip through main will' play the tune again, anyway). The second button command, which' scrolls through the selection LEDs, uses both debounce and auto-' repeat. Switch bounce could cause the display to seem to skip' over selections, and autorepeat is a nice, professional touch' for rapidly scrolling through the display.

    Main:button 7,0,0,0,b0,0,no_play ' Don't play tune unless button is pushed.branch Select,(Tune0,Tune1,Tune2,Tune3,Tune4)

    no_play:button 6,0,200,60,b1,1,Pick ' When button is pushed, change selection.

    goto Main

  • 8/7/2019 bs1Appnotes

    94/126

  • 8/7/2019 bs1Appnotes

    95/126

  • 8/7/2019 bs1Appnotes

    96/126

  • 8/7/2019 bs1Appnotes

    97/126

    BASIC Stamp I Application Notes 20: An Accurate Timebase

    it to a u sable form , you h ave p retty m uch filled th e Stamp s EEPROM.A compr omise app roach is to provid e the Stamp with a very accur atesource of timing p ulses, and let your p rogram d ecide how to use them.The circuit and example progr am p resented here d o just that. For thisdemonstration, the Stamp counts the passing seconds and displaysthem using debug .

  • 8/7/2019 bs1Appnotes

    98/126

    Page 168 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    them using debug .

    How it works. The circuit in figure 1 show s how to construct a crystal-controlled, 2-pu lse-per-second timebase from a common digital part,the CD4060B. This part costs less than $1 from mail-order companieslike the one listed a t the en d o f this note. The 32,768-Hz crystal is alsoinexpen sive, at just over 50 cents.

    The 4060 is a 14-stage binary counter with an onboard oscillator.Althoug h th e oscillator can be used with a resistor/ capacitor timingcircu it, were going for accuracy; hence the crystal. Why 32,768 Hz andnot som e other value, like 1 MHz? It just hap pen s that 32,768 = 2 15, so itseasy to use a binary counter like the 4060 to divide it down to easyfractions of one second . Since the 4060 is a 14-stage coun ter, the best itcan do is divide by 2 14. The pr ogram further d ivides the resulting tw ice-a-second p ulses to pr odu ce one count per second.

    Take a look at the program listing. It consists of a main loop and arou tine to increment th e clock. In an actual app lication, the m ain loopw ould contain m ost of the prog ram instru ctions. For accur ate timing,the instru ctions w ithin the m ain loop m ust tak e less than 250 millisec-onds total. Even with the timing problems weve discussed, thats

    pr etty easy to do.

    Lets walk th rou gh th e progr ams logic. In th e main loop, the p rogramcompares th e state of pin0 to bit0 . If theyre equ al (both 0 or both 1) itjum ps to the tick routine.

    In tick , the program toggles bit0 by ad ding 1 to the byte it belongs to, b0.This makes sure that bit0 is no longer equ al to the state of pin0 , so the

    program w ont return to tick until pin0 changes again.

    B0 also serves as a coun ter. If it is less than 4, the program retur ns to th emain loop. When b0 reaches 4, tick clears it, add s 1 to the run ning total

  • 8/7/2019 bs1Appnotes

    99/126

  • 8/7/2019 bs1Appnotes

    100/126

    BASIC Stamp I Application Notes21: Fun with Trains

    Introduction. This application note describes a simple model trainpr oject that w e show ed at the Embed ded Systems Conference in 1994.The project u ses a Stamp to control the speed s of three N -scale trains.The speeds are displayed on a n LCD display, and can be chan ged u singthree buttons: track select , up , and down .

  • 8/7/2019 bs1Appnotes

    101/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 171

    1

    Background. Several months before the Conference, we decided thatw e shou ld h ave an interesting exam ple of the Stamp s capabilities. Wedetermined that it should be something physical, something simple,and something tha t people wou ld relate to. We looked at various toys,includ ing Legos, Erector Sets, electric race cars, and mod el trains. Theyall had their good and bad p oints, but we finally decided up on mod eltrains. I always liked m odel trains as a child, and I w as the one w ho hadto build it, anyw ay.

    Trains are somew hat simp le to control and detect, and man y peop le likethem (mor e than w e expected). The only draw back was the amazinglyhigh cost of constructing a comp lete train set. A comp lete train set, withthr ee loops of track, thr ee trains, several build ings, and lots of trees, costabout $700! (the trains my paren ts bough t w ere mu ch less expensive).It didn t seem like that m uch, because I pu rchased the track one d ay,and the engines a w eek later, and the bu ild ings a week later, etc. But th e

    bookkeeper w as keeping track, and ind eed the simp le train display wasgetting expensive. But , alas, it was too late to go back.

    Having d ecided u pon a train set, I had the harder task of deciding wh at

    The completed Stamp-controlled train set(buildings and treeswere added later).

    BASIC Stamp I Application Notes 21: Fun with Trains

    to d o w ith it. I had some really neat ideas, like having a Stamp in eachengine, thus m aking each train intelligent. With a brain in each train, Iwould then have infrared markers along the track, so the trainsw ould k now their position and act accord ingly. In fact, perh aps theycould even communicate with a master Stamp, which could thenmod ify their path and commu nicate with oth er trains. The possibilities

    dl ll h d l

  • 8/7/2019 bs1Appnotes

    102/126

    Page 172 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    were endless, especially since I hadnt run into reality, yet.

    After some hu mbling thought, I tapered m y ideas to a simple two-partgoal: to control the speed of three trains, and to detect the position of thetrains. I didn t know exactly how to accomp lish th ese goals, but th ey

    seemed p ossible. I knew th at high-current d rivers existed , and could beused to run the trains. As for detecting the trains, my th ough ts rangedfrom LED/ d etector pairs to H all-effect sensors. The H all-effect sensorsseemed better, since they could be hidd en (LEDs wou ld be too obvious).

    Preliminary research. Not know ing mu ch about h igh-current drivers,I called Scott Edw ard s. H e knows som ething about everyth ing, and hew as hap py to fax a pinou t of the Motorola ULN2803. The Motorola chip

    is an 18-pin device described as an octal high-voltage, high-cur rentDarlington transistor array. Other p eople refer to it as a low-sid edr iver, since its used to d rive the low (GND) side of a load. Eachdr iver can sink 500 mA, and as you might gu ess from the w ord octalin the n ame, the ULN2803 has eight separate d rivers, so you can reallydr ive a lot of cur rent w ith one chip. The chip even has intern al clampingdiod es to sup pr ess transients that occur w hen noisy devices tur n onand off (noisy d evices includ e motors, relays, solenoid s, etc.). With-

    out diod es to sup press tran sients, the digital control circuitry (in thiscase, the Stamp ) may go crazy (I think th is is caused by fluctuations onthe I/ O pins an d/ or pow er pins). In an y case, the ULN2803 makes apr eviously messy task very clean, simp le, and inexpensive (the chipsare un der $1).

    As for Hall-effect sensor s, I ord ered a selection from Digi-Key and thenw ent to Radio Shack to bu y some m agnets. If youre not familiar with

    them, Hall-effect sensors are 3-pin, transistor-sized devices that sensemagn etic fields. They sense the p resence of a north or south magn eticfield, dep end ing on th e individu al sensors design. Some even act as amechanical sw itch: they trigger w hen a m agnetic field is present, and

  • 8/7/2019 bs1Appnotes

    103/126

  • 8/7/2019 bs1Appnotes

    104/126

  • 8/7/2019 bs1Appnotes

    105/126

    BASIC Stamp I Application Notes 21: Fun with Trains

    had never u sed th e BUTTON instruction before, but it w as relativelysimp le to experiment with and und erstand.

    But, I noticed that th e button s seemed un stable; sometimes th e Stampw ould act as if I were still pressing a button long after I had stop ped .Then I realized that I had forgotten pull-up resistors on the buttoninputs. In my circuit, when a button was pressed, it connected the

  • 8/7/2019 bs1Appnotes

    106/126

    Page 176 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    inputs. In my circuit, when a button was pressed, it connected theassociated I/ O pin to gr oun d, w hich read as 0 to the BASIC program .How ever, wh en the button w as not pressed, the I/ O pin w ould float,since it wasnt connected to anything. Since the pin was floating, itw ould rand omly read as 0 or 1. This was solved by add ing pu ll-up

    resistors to the bu tton inp uts; the resistors prov ide a w eak conn ectionto the 5-volt sup ply, so the inpu ts read as 1 w hen th eir buttons are n otpressed. The last step involving the buttons was to adjust the auto-repeat rate u ntil it seemed right (not too fast, not too slow). The repeatrate is controlled by on e of the values given in th e BUTTON instruction,so it just took a few qu ick dow nloads to arrive at the right valu e.

    Connecting the LCD display. With the buttons working, the next itemw as the LCD. I conn ected th e LCD to the Stamp and then entered thesample program provided with the LCD. After some minor trou ble-shooting, the LCD wor ked, and wor ked w ell! Printing text was almostas easy as using th e norm al PRINT instru ction found in other versions

    of BASIC. But, since the Stamp has n o PRINT instr uction, th e LCD iscontrolled with simple SEROUT instructions. For instance, SEROUT0,N2400,(hello)pr ints the word hello on an LCD modu le connectedto pin 0.

    76543210

    +5V

    Vin

    GND 1993REV D

    BASIC StampTM

    U L N 2 8 0 3 A

    SEL

    +

    Completed Stamp with ULN2803 and buttons

  • 8/7/2019 bs1Appnotes

    107/126

    BASIC Stamp I Application Notes 21: Fun with Trains

    to set each speed to zero, wh ich w ould take some time (I imagined tr ainsstrewn about th e board). The pan ic button was easy: all I needed to ad dw as a single line in the beginning of the m ain loop, wh ich w ould check

    the pan ic button and jum p to an earlier line that set the speeds to zero(something that the p rogram d id u pon start-up ). This seemed straight-forward , but it proved to be m ore difficult than I thou ght. The conceptw as fine, but I was short a few bytes of progr am sp ace.

  • 8/7/2019 bs1Appnotes

    108/126

    Page 178 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    A few more bytes. Squeezing a few more bytes out of my p rogram w aspainfully d ifficult. Finally, everything did fit, but only after resorting toextreme measu res. For instan ce, if you look at the first few lines of cod e,

    you ll see the follow ing:

    symbol track1_speed=b2symbol track1_accum=b1

    symbol track2_speed=b3symbol track2_accum=b7

    symbol track3_speed=b4symbol track3_accum=b6

    symbol current_track = b5...reset: w1 = 0: w2 = 0

    You m ight won der w hy I did nt just u se the variables b1-b7 in order,wh ich is how I originally had th em. The order show n seems rand om,but it actually saves program space later. The last line show n resets thetrack speeds and current track variable. The word variable w1includesb2an d b3, and the word variable w2includes b4and b5. So, by clearin gtwo w ord variables, the program clears four byte variables, which savesa byte or two of program space.

    If youre really won dering about variable allocation, you m ight alsowon der w hy the program doesnt store anything in b0. This is becauseb0 has a sp ecial role in the train PWM r outine:

  • 8/7/2019 bs1Appnotes

    109/126

  • 8/7/2019 bs1Appnotes

    110/126

  • 8/7/2019 bs1Appnotes

    111/126

    BASIC Stamp I Application Notes

    gosub run_trains 'update track pwm

    done: b0 = current_track * 4 + 130 'print arrow pointing toserout 6,n2400,(254,b0,254,">") 'currently selected track

    goto main_loop

    run_trains:

    'update track 1 pwm

    21: Fun with Trains

  • 8/7/2019 bs1Appnotes

    112/126

    Page 182 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    update track 1 pwmtrack1_accum = track1_accum + track1_speedb0 = track1_accumpin3 = bit7 'drive track 1track1_accum = track1_accum & %01111111

    'update track 2 pwmtrack2_accum = track2_accum + track2_speedb0 = track2_accumpin4 = bit7 'drive track 2track2_accum = track2_accum & %01111111

    'update track 3 pwmtrack3_accum = track3_accum + track3_speedb0 = track3_accum

    pin5 = bit7 'drive track 3track3_accum = track3_accum & %01111111

    return

    BASIC Stamp I Application Notes22: Interfacing a 12-bit ADC

    Introduction. This app lication note sh ows how to interface the LTC1298ana log-to-digital converter (ADC) to the BASIC Stam p.

    Background. Many p opu lar applications for the Stamp includ e analogmeasu remen t, either using the Pot comm and or an external ADC. Thesemeasu remen ts are limited to eight-bit resolution, meaning that a 5-voltfu l l - sca le measurement would be b roken in to un i t s o f 5/ 256 = 19 5 millivolts (m V)

  • 8/7/2019 bs1Appnotes

    113/126

    Parallax, Inc. BASIC Stamp Programming Manual 1.9 Page 183

    15/ 256 19.5 millivolts (m V).

    That sound s pretty good u ntil you app ly it to a real-w orld sensor. Takethe LM34 and LM35 temp eratur e sensors as an examp le. They outp ut

    a voltage pr oportional to the ambient temp eratur e in d egrees Fahren-heit (LM34) or Centigrade (LM35). A 1-degree change in temperaturecauses a 10-mV change in the sensors output voltage. So an eight-bitconversion gives lousy 2-degree resolution. By reducing the ADCsrange, or amp lifying th e sensor signal, you can impr ove resolution, butat the expense of ad ditional comp onents and a less-general design.

    The easy way out is to switch to an ADC w ith 10- or 12-bit resolution.

    Until recently, that h asnt been a d ecision to make lightly, since m orebits = more bucks. How ever, the new LTC1298 12-bit ADC is reason-ably pr iced at less than $10, and gives your Stamp pr ojects two channels

    Schematic to accompany LT C1298.BA S

    1k

    +5

    10Ftantalum+

    5kpot

    5kpot

    +5

    pin 0 pin 2 pin 1

    Connections to BASIC Stamp I/O pins

    Variable VoltageSource for Demo

    05V in

    CS

    CH0

    CH1

    GND

    Vcc

    CLK

    Dout

    Din

    LTC1298

    1

    BASIC Stamp I Application Notes

    of 1.22-mV resolution d ata. Its packaged in a Stamp -friend ly 8-pin D IP,and dr aw s about 250 microamp s (A ) of cur rent.

    How it works. The figure shows how to connect the LTC1298 to theStamp, and the listing supplies the necessary driver code. If youhave used other synchronous serial devices with the Stamp, such asEEPROMs or other ADCs described in previous application notes,there are n o sur prises here. We have tied th e LTC1298s data inpu t and

    22: Interfacing a 12-bit ADC

  • 8/7/2019 bs1Appnotes

    114/126

    Page 184 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    t e e a e o su p ses e e. We ave t ed t e C 98 s data pu t a doutp ut together to take ad vantage of the Stamp s ability to switch d atadirections on the fly. The resistor limits the current flowing betw een theStamp I/ O p in and th e 1298s data outp ut in case a progr amm ing error

    or other fault causes a bus conflict. This happ ens w hen both pins arein output mode and in opposite states (1 vs. 0). Without the resistor,such a conflict would cause large currents to flow between pins,possibly damaging the Stamp and/ or ADC.

    If you have u sed oth er ADCs, you m ay hav e noticed th at the LTC1298has no voltage-reference (Vref) pin. The voltage reference is what anADC compar es its analog inpu t voltage to. When th e analog voltage is

    equal to the reference voltage, the ADC ou tpu ts its maximu m m easure-men t value; 4095 in this case. Smaller inp ut voltages result in p rop or-tionally smaller output values. For example, an input of 1/ 10th thereference voltage w ould pr odu ce an ou tpu t value of 409.

    The LTC1298s voltage reference is intern ally conn ected to th e pow ersupp ly, Vcc, at pin 8. This m eans th at a full-scale read ing of 4095 willoccur when the input voltage is equal to the power-supply voltage,

    nom inally 5 volts. Notice the weasel word nom inally, meaning innam e only. The actual voltage at th e +5-volt rail of the full-size (pre-BS1-IC) Stam p w ith th e LM2936 regulato r can be 4.9 to 5.1 volts initially,and can vary by 30 mV.

    In some ap plications youll need a calibration step to comp ensate for thesupply voltage. Suppose the LTC1298 is looking at 2.00 volts. If thesu pply is 4.90 volts, the LTC1298 will measu re (2.00/ 4.90) * 4095 = 1671.

    If the supply is at the other extreme, 5.10 volts, the LTC1298 willmeasure (2.00/ 5.10) * 4095 = 1606.

    How about that 30-mV deviation in regulator performance, which

  • 8/7/2019 bs1Appnotes

    115/126

    BASIC Stamp I Application Notes

    ' Program: LTC1298.BAS (LTC1298 analog-to-digital converter)' The LTC1298 is a 12-bit, two-channel ADC. Its high resolution, low' supply current, low cost, and built-in sample/hold feature make it a' great companion for the Stamp in sensor and data-logging applications.

    ' With its 12-bit resolution, the LTC1298 can measure tiny changes in' input voltage; 1.22 millivolts (5-volt reference/4096).

    ' ==========================================================' ADC Interface Pins' ==========================================================

    22: Interfacing a 12-bit ADC

  • 8/7/2019 bs1Appnotes

    116/126

    Page 186 BASIC Stamp Programming Manual 1.9 Parallax, Inc.

    ' The 1298 uses a four-pin interface, consisting of chip-select, clock,' data input, and data output. In this application, we tie the data lines' together with a 1k resistor and connect the Stamp pin designated DIO

    ' to the data-in side of the resistor. The resistor limits the current' flowing between DIO and the 1298s data out in case a programming error' or other fault causes a bus conflict. This happens when both pins are' in output mode and in opposite states (1 vs 0). Without the resistor,' such a conflict would cause large currents to flow between pins,' possibly damag