Bs 2 Tutorial

Embed Size (px)

Citation preview

  • 8/7/2019 Bs 2 Tutorial

    1/188

    11

    Parallax BASIC StampParallax BASIC Stamp TutorialTutorial

    Developed by:Developed by:Electronic Systems TechnologiesElectronic Systems TechnologiesCollege of Applied Sciences and ArtsCollege of Applied Sciences and ArtsSouthern Illinois University CarbondaleSouthern Illinois University Carbondalehttp://www.siu.edu/~imsasa/http://www.siu.edu/~imsasa/ estest

    Martin HebelMartin [email protected]@siu.edu With support from:With support from:Will Devenport, Mike Palic and Mike SinnoWill Devenport, Mike Palic and Mike Sinno

    Sponsored by:Sponsored by:

    Parallax, Inc.Parallax, Inc.http://www.parallax.com/http://www.parallax.com/

    Updated: 3/14/03 Version 1.0

    2

    Copyright NoticeCopyright NoticeCopyright 2002, Parallax, Inc.Copyright 2002, Parallax, Inc.BASIC Stamp is a registered trademark of Parallax, Inc.BASIC Stamp is a registered trademark of Parallax, Inc.

    Parallax, Inc. and participating companies are notParallax, Inc. and participating companies are notresponsible for special, incidental, or consequentialresponsible for special, incidental, or consequentialdamages resulting from any breach of warranty, or under damages resulting from any breach of warranty, or under any legal theory, including lost profits, downtime, goodwill,any legal theory, including lost profits, downtime, goodwill,damage to or replacement of equipment or property, nor damage to or replacement of equipment or property, nor any costs of recovering, reprogramming, or reproducingany costs of recovering, reprogramming, or reproducingany data stored in or used with Parallax products.any data stored in or used with Parallax products.

    Unmodified distribution of this tutorial is allowed.Unmodified distribution of this tutorial is allowed.

    Modifications to this tutorial are authorized for educationalModifications to this tutorial are authorized for educational

    use internal to the schools program of study. Thisuse internal to the schools program of study. Thiscopyright notice and development credits must remain.copyright notice and development credits must remain.

  • 8/7/2019 Bs 2 Tutorial

    2/188

    3

    Use of the TutorialUse of the TutorialThis tutorial is for novices in programming the BS2This tutorial is for novices in programming the BS2from Parallax, Inc. For advanced use please refer tofrom Parallax, Inc. For advanced use please refer toyour BASIC Stamp Manual, help files and other your BASIC Stamp Manual, help files and other sources.sources.

    The tutorial uses the Board of Education (BOE) asThe tutorial uses the Board of Education (BOE) asthe primary carrier board for the BS2, though other the primary carrier board for the BS2, though other boards and configurations may also be used.boards and configurations may also be used.

    The majority of the tutorial is compatible with theThe majority of the tutorial is compatible with theHomeWork board and the BASIC Stamp ActivityHomeWork board and the BASIC Stamp ActivityBoard except where noted.Board except where noted.

    We welcome any constructive feedback you wish toWe welcome any constructive feedback you wish toprovide. A feedback page and survey are located at:provide. A feedback page and survey are located at:http://imsinet.casa.siu.edu/bs2_tutorial/feedback.http://imsinet.casa.siu.edu/bs2_tutorial/feedback. htmhtmIf this link is no longer active, please contactIf this link is no longer active, please contactParallax atParallax at stampsinclassstampsinclass @[email protected] ..

    4

    Parts RequiredParts RequiredThis tutorial was written to use a minimum number This tutorial was written to use a minimum number of inexpensive components as possible inof inexpensive components as possible inteaching the basic principles.teaching the basic principles.

    The following are recommended:The following are recommended:A BASIC Stamp 2 and aA BASIC Stamp 2 and a carrier boardcarrier board , such as the, such as theBOE, HomeWork Board, Activity Board or NX-1000,BOE, HomeWork Board, Activity Board or NX-1000,cables and software.cables and software.Parts for Sections 4-7:Parts for Sections 4-7:(3) 220 Ohm Resistors(3) 220 Ohm Resistors(2) LEDs(2) LEDs(2) N.O. Momentary Pushbuttons(2) N.O. Momentary Pushbuttons(2) 1K Ohm Resistors(2) 1K Ohm Resistors(1) 0.1 microfarad capacitor (1) 0.1 microfarad capacitor (1) 100K Ohm Potentiometer (1) 100K Ohm Potentiometer (1) Piezoelectric Speaker (1) Piezoelectric Speaker

    Additional Parts for Sections 8,9Additional Parts for Sections 8,9(1) 10K Ohm Resistor (1) 10K Ohm Resistor (1) 10uF Capacitor (1) 10uF Capacitor (1) ADC0831(1) ADC0831(1) LM34 Temperature Sensor (1) LM34 Temperature Sensor

  • 8/7/2019 Bs 2 Tutorial

    3/188

    55

    ContentsContents

    Operation, Device I/O,Memory, Serial Programming,Versions, BOE

    1: BASIC Stamp Anatomy & BOE

    Power, I/O Connections,HomeWork Board, BSAC, NX-1000, OEM,

    Solder Boards

    2: Other Carrier Boards

    Physical Connection, Verifying ConnectionWriting Code, R unning Code, Using Help

    3: BASIC Stamp Editor

    Digital Outputs: HIGH/LOW, OUTPUT, OUT.Digital Inputs: INPUT, IN DEBUG, DIRSAnalog Input: RCTIMEFrequency Output: FREQOUT

    4: Input, Processing, and Output

    Memory Variables, Constants, I/O Aliases

    5: Variables and Aliases

    Sequential flow, Branching and Looping.Conditionals: GOTO, IF.. THEN, FOR.. NEXT.Subroutines: GOSUB BRANCHPower Saving: END, SLEEP

    6: Program Flow

    DEBUG Modifiers, Math Operations,, Booleanoperations, LOOKUP, WRITE & READ, DATA

    7: Math and Data Operations

    SHIFTIN, SHIFTOUTSERIN, SEROUT

    PULSEIN, PULSOUT, PWM

    8: Communications and Control

    Decimal, Binary , Hexadecimal

    Binary Coded DecimalASCII

    App. B: Number Systems

    GoGo

    GoGo

    GoGo

    GoGo

    GoGo

    GoGo

    GoGo

    GoGo

    GoGo

    HomeHome Schematics Sec. 4-7Schematics Sec. 4-7

    Schematics Sec. 8Schematics Sec. 8

    StampPlot Lite, Standard/ProStampDAQOPTAScope

    9: Data Acquisition

    GoGo

    LinksLinks

    PIN, IF..THEN..ELSE, SELECT..CASE,DO..LOOP, ON..GOTO, ON..GOSUB,DEBUGIN

    App. A: PBASIC 2.5 Revisions

    GoGo

    6

    Section 1:Section 1: BASIC Stamp 2 AnatomyBASIC Stamp 2 AnatomyMicrocontrollersMicrocontrollersBASIC Stamp ComponentsBASIC Stamp Components

    BASIC Stamp 2 PinsBASIC Stamp 2 PinsBASIC Stamp 2 VersionsBASIC Stamp 2 VersionsRunning a ProgramRunning a ProgramCarrier and Experiment BoardsCarrier and Experiment BoardsPower ConnectionsPower ConnectionsData ConnectionsData ConnectionsSerial Data ConnectorsSerial Data ConnectorsI/O ConnectionsI/O ConnectionsComponent Power ConnectionsComponent Power ConnectionsConnecting ComponentsConnecting ComponentsBreadboard ConnectionsBreadboard Connections

    Other FeaturesOther Features

  • 8/7/2019 Bs 2 Tutorial

    4/188

    7

    MicrocontrollersMicrocontrollersMicrocontrollers can be thought of as very small computersMicrocontrollers can be thought of as very small computerswhich may be programmed to control systems such as cellwhich may be programmed to control systems such as cellphones, microwave ovens, toys, automotive systems, etc.phones, microwave ovens, toys, automotive systems, etc.

    A typical household has upwards of 25 to 50 microcontrollersA typical household has upwards of 25 to 50 microcontrollersperformingperforming embedded control embedded control in numerous appliances andin numerous appliances anddevices.devices.

    The BASIC Stamps are hybrid microcontrollers which areThe BASIC Stamps are hybrid microcontrollers which aredesigned to be programmed in a version of thedesigned to be programmed in a version of the BASIC BASIC programming language calledprogramming language called PBASIC PBASIC ..

    Hardware support on the module allows fast, easyHardware support on the module allows fast, easyprogramming and use.programming and use.

    8

    BASIC Stamp Module ComponentsBASIC Stamp Module Components

    5V Regulator Regulates voltageto 5V with a supply of 5.5VDC to 15VDC

    Resonator Sets the speed at whichinstructions are processed.

    EEPROMStores the tokenizedPBASIC program.

    Interpreter ChipReads the BASICprogram from theEEPROM and executesthe instructions.

    Serial SignalConditioningConditions voltagesignals between PC serialconnection (+/- 12V) andBASIC Stamp (5V)

  • 8/7/2019 Bs 2 Tutorial

    5/188

    9

    BASIC Stamp 2 PinsBASIC Stamp 2 PinsPin 1: S OUT

    Transmits serial data duringprogramming and using theDEBUG instruction

    Pin 2: S INReceives serial data duringprogramming

    Pin 3: ATNUses the serial DTR line togain the Stamps attentionfor programming.

    Pin 4. V SSCommunicationsGround (0V).

    P0

    Pins 5-20:Input/Output (I/O)pins P0 through P15

    P1P2P3P4P5P6P7 P8

    P9P10P11P12P13P14P15

    Pin 21. V DDRegulated 5V.

    Pin 22. RESReset- LOW toreset

    Pin 23. V SSGround (0V)

    Pin 24. V INUn-regulatedinput voltage(5.5-15V)

    10

    BASIC Stamp 2 VersionsBASIC Stamp 2 VersionsThere are several versions of the BASIC Stamp. This tutorial has beenThere are several versions of the BASIC Stamp. This tutorial has beenwritten for the BASIC Stamp 2 (BS2) series of controllers.written for the BASIC Stamp 2 (BS2) series of controllers.

    Each BASIC Stamp has different features, below are the most popular:Each BASIC Stamp has different features, below are the most popular:

    26 Bytes of RAM63 bytes of scratchpad memory

    50MHz10,000 instructions/second

    16K Bytes in8 2K banks.4000 lines of code

    BS2sx

    26 Bytes of RAM20MHz4000 instructions/second

    2K Bytes500 lines of code

    BS2

    I2C, Dallas 1- Wire,LCD, polling

    capabilities.16 extra I/O on 40pin version.

    20 MHz Turbo16K Bytes in8 2K banks.

    4000 lines of code.

    BS2p24 and 40 pinsversions

    26 Bytes of RAMLess expensive, easyto replacecomponents.

    20MHz4000 instructions/second

    2K Bytes500 lines of code

    BS2 OEM

    AdditionalFeatures

    SpeedMemoryVersion

  • 8/7/2019 Bs 2 Tutorial

    6/188

    11

    Running a ProgramRunning a Program

    A program is writtenA program is writtenin the BASIC Stamp Editor in the BASIC Stamp Editor

    The Interpreter Chip reads theThe Interpreter Chip reads theprogram from EEPROM andprogram from EEPROM andexecutes the instructions readingexecutes the instructions readingand controlling I/O pins. Theand controlling I/O pins. Theprogram will remain in EEPROMprogram will remain in EEPROMindefinitely with or without power indefinitely with or without power applied.applied.

    The program is tokenized,The program is tokenized,or converted into symbolic format.or converted into symbolic format.

    Tokenizer The tokenized program isThe tokenized program is

    transmitter through the serial cabletransmitter through the serial cableand stored in EEPROM memory.and stored in EEPROM memory.

    12

    Carrier and Experiment BoardsCarrier and Experiment BoardsThe user may engineer their own power, communicationsThe user may engineer their own power, communicationsand control circuits for the BASIC Stamp, but for beginnersand control circuits for the BASIC Stamp, but for beginners

    an assortment of carrier and experimenter boards arean assortment of carrier and experimenter boards areavailable for ease of development and testing.available for ease of development and testing.

    The Board of Education (BOE) is one such board and willThe Board of Education (BOE) is one such board and willbe the focus for this tutorial.be the focus for this tutorial.

    Note the notchNote the notchat the top of theat the top of theBASIC Stamp andBASIC Stamp andsocket indicatingsocket indicatingmodule direction.module direction.

  • 8/7/2019 Bs 2 Tutorial

    7/188

    13

    Power ConnectionsPower Connections

    The Board of EducationThe Board of Educationmay be powered frommay be powered fromeither:either:

    6-15VDCWall Transformer,

    center positive.

    9V Battery

    Many carrier boards, suchas the BOE, have an

    additional 5V regulator tosupplement the on-module

    regulator.

    14

    Data ConnectionsData ConnectionsA serial cable (modem cable) is connectedA serial cable (modem cable) is connectedbetween BASIC Stamp and the computers serialbetween BASIC Stamp and the computers serial

    communication port (COM port).communication port (COM port).Serial means that data is sent or received one bit at aSerial means that data is sent or received one bit at atime.time.The serial cable is used to download the stamp with theThe serial cable is used to download the stamp with theprogram written in the text editor and is sometimes usedprogram written in the text editor and is sometimes usedto display information from the BASIC Stamp using theto display information from the BASIC Stamp using theDEBUG instruction.DEBUG instruction.Ensure that you use are using aEnsure that you use are using aStraight-ThroughStraight-Through cable (pins 2cable (pins 2and 3 do not cross fromand 3 do not cross fromend-to-end) as opposed to aend-to-end) as opposed to aNull-ModemNull-Modem cable (pins 2 andcable (pins 2 and

    3 cross).3 cross).There are different connectors for There are different connectors for different computer hardware.different computer hardware.

  • 8/7/2019 Bs 2 Tutorial

    8/188

    15

    Serial Data ConnectorsSerial Data Connectors

    The cable is typically connectedThe cable is typically connectedto an available DB 9 COM port.to an available DB 9 COM port.

    A DB 25 to DB 9A DB 25 to DB 9adapter mayadapter maybe needed onbe needed on

    older systemsolder systems

    Newer systems mayNewer systems mayonly have USB portsonly have USB portsand require a USB-to-and require a USB-to-Serial Adapter.Serial Adapter.

    16

    I/O ConnectionsI/O ConnectionsCode, such asCode, such as HIGH 8HIGH 8 will be written for thewill be written for theBASIC Stamp. This instruction will control aBASIC Stamp. This instruction will control adevice connected to P8 of the controller.device connected to P8 of the controller.

    The P8 connection isThe P8 connection isavailable on the header available on the header next to the breadboardnext to the breadboardarea.area.

    A connection to the I/O pinsA connection to the I/O pinsis also available on theis also available on theApp-Mod header.App-Mod header.

  • 8/7/2019 Bs 2 Tutorial

    9/188

    17

    Component Power ConnectionsComponent Power ConnectionsPower for the components are available onPower for the components are available onheaders also.headers also.

    +5V (Vdd)+5V (Vdd) 0V or ground (Vss)0V or ground (Vss) Supply Voltage (Vin)Supply Voltage (Vin)

    NOTE: Use of Vinmay cause damagingvoltages to be appliedto the BASIC Stamp.

    Use only under directeduse!

    18

    Connecting ComponentsConnecting ComponentsOf course, an important aspect to any BASIC StampOf course, an important aspect to any BASIC Stampproject are the components that will be connected to theproject are the components that will be connected to the

    I/O pins of the Stamp.I/O pins of the Stamp.

    The carrier boards allow quick connections for theThe carrier boards allow quick connections for thecomponents.components.

  • 8/7/2019 Bs 2 Tutorial

    10/188

    19

    Breadboard ConnectionsBreadboard Connections

    Breadboard are rows of connectors used to electricallyBreadboard are rows of connectors used to electricallyconnect components and wiring.connect components and wiring.

    Each row in each half Each row in each half of the breadboard areof the breadboard areelectrically the same point.electrically the same point.

    Components areComponents areconnected between rows and toconnected between rows and tothe headers to make electricalthe headers to make electricalconnections.connections.

    There exist no connectionsThere exist no connectionsbetween the headers and thebetween the headers and thebreadboards or in columns onbreadboards or in columns onthe breadboard.the breadboard.

    Components should NOTComponents should NOTbe connected on a single rowbe connected on a single rowor they will be shorted out of or they will be shorted out of

    the circuit.the circuit.

    20

    This image is theThis image is the

    Board of EducationBoard of Educationwith severalwith severalcomponentscomponentsconnected.connected. The connectionsThe connectionson the breadboardon the breadboardcreate a completecreate a completepath for currentpath for currentto flow.to flow.

    I/OI/OPinPin

    Vdd (5V)Vdd (5V)

  • 8/7/2019 Bs 2 Tutorial

    11/188

    21

    Other FeaturesOther Features

    Reset Button to restart theReset Button to restart theprogram on the BASIC Stampprogram on the BASIC Stamp

    Servo Header ConnectorsServo Header Connectors

    Power-On LEDPower-On LED

    ProgrammingProgrammingPortPort

    22

    SummarySummaryThe BASIC Stamp is like a miniatureThe BASIC Stamp is like a miniature

    computer that can be programmed to readcomputer that can be programmed to readand control Input/Output pins.and control Input/Output pins.

    Programs written on a PC are tokenized,Programs written on a PC are tokenized,serially transmitted and stored in the BASICserially transmitted and stored in the BASICStamp's EEPROM.Stamp's EEPROM.

    The Board of Education provides a meansThe Board of Education provides a meansof programming and connecting devices toof programming and connecting devices to

    the BASIC Stamp.the BASIC Stamp.

  • 8/7/2019 Bs 2 Tutorial

    12/188

    23

    End of Section 1End of Section 1

    24

    Section 2: Other Carrier BoardsSection 2: Other Carrier BoardsBasic Stamp HomeWork BoardBasic Stamp HomeWork Board

    BASIC Stamp Activity BoardBASIC Stamp Activity BoardNX-1000NX-1000Solder Carrier BoardSolder Carrier BoardOEM moduleOEM module

  • 8/7/2019 Bs 2 Tutorial

    13/188

    25

    Other Programming BoardsOther Programming Boards

    While this tutorial focuses on the Board of While this tutorial focuses on the Board of Education (BOE) carrier board, there are manyEducation (BOE) carrier board, there are many

    others which may be used.others which may be used.All the boards have:All the boards have:Power Connectors.Power Connectors.Communications ports.Communications ports.P-numbered I/O connections.P-numbered I/O connections.Many have a separate 5V regulator for devices.Many have a separate 5V regulator for devices.

    26

    BASIC Stamp HomeWork BoardBASIC Stamp HomeWork BoardThe HomeWork Board is an inexpensiveThe HomeWork Board is an inexpensive

    alternative for student projects.alternative for student projects.The BASIC Stamp isThe BASIC Stamp isintegral to the boardintegral to the boardinstead of a separateinstead of a separatemodule.module.

    All I/O have 220 ohmAll I/O have 220 ohmcurrent limiting resistors.current limiting resistors.This means that the 220This means that the 220ohm resistors used forohm resistors used forconnections in this tutorialconnections in this tutorialmay be omitted.may be omitted.

  • 8/7/2019 Bs 2 Tutorial

    14/188

    27

    BASIC Stamp Activity BoardBASIC Stamp Activity BoardThe BASIC Stamp Activity Board is great board for The BASIC Stamp Activity Board is great board for novice users because it has commonly usednovice users because it has commonly useddevices which are pre-connected to the BASICdevices which are pre-connected to the BASIC

    Stamp allowing quick program testing.Stamp allowing quick program testing.

    On-Board devices:On-Board devices: 4 buttons4 buttons 4 LEDs4 LEDs Speaker Speaker Potentiometer Potentiometer X10 power line interfaceX10 power line interface Sockets for specific add-on ICsSockets for specific add-on ICs

    28

    Each device is numbered, such as the blue button/LEDEach device is numbered, such as the blue button/LEDwith P7/8 (the switch is used for input, the LED is used for with P7/8 (the switch is used for input, the LED is used for output).output).

    The 1The 1 stst number is the I/O number if you are using a BASIC Stamp I.number is the I/O number if you are using a BASIC Stamp I.The 2The 2 ndnd number is the I/O number if you are using the BASIC Stamp 2number is the I/O number if you are using the BASIC Stamp 2family.family.Code such as HIGH 8 will operate the blue button/LED combinationCode such as HIGH 8 will operate the blue button/LED combination

    with the BS2.with the BS2.Code in this tutorial is compatible with this board except where noted.Code in this tutorial is compatible with this board except where noted.

    Programs inthis tutorial will notwork with the BS1.

  • 8/7/2019 Bs 2 Tutorial

    15/188

    29

    NX-1000NX-1000This board is a great experimenter's board. It has a wide variety of This board is a great experimenter's board. It has a wide variety of devices which are NOT pre-connected.devices which are NOT pre-connected.

    A large breadboard area accommodates many other devices.A large breadboard area accommodates many other devices.

    7-SegmentLED Display

    Current-Limited LEDs

    AudioAmp

    LCDHeader

    Speaker & Pot

    High-CurrentDrivers

    Active-Low switchesSelectableOscillator

    Spare SerialConnector

    Jumper wires areused betweenheaders to connectdesired devices toI/O pins.

    ProgrammingSerial Connector

    30

    Through-Hole Solder Carrier BoardThrough-Hole Solder Carrier BoardFor more permanent construction, boards with solder For more permanent construction, boards with solder connections are available.connections are available.

  • 8/7/2019 Bs 2 Tutorial

    16/188

    31

    OEM moduleOEM moduleThe BASIC Stamp 2The BASIC Stamp 2OEM is a discreetOEM is a discreetcomponent version of component version of

    the BS2 which may bethe BS2 which may bepurchased in kit form.purchased in kit form.The male header The male header provides the means toprovides the means toplug-it into your ownplug-it into your ownboard, or connect toboard, or connect toother boards.other boards.

    Regulated 5V (Vdd)

    Ground- 0V (Vss)

    5.5 15V input (Vin)

    Reset Input (RES)

    P0-P15 I/O

    Power the board with EITHER:A) 5.5-15VDC on Vin. This willalso provide 5VDC regulatedoutput on Vdd.

    B) Regulated 5V Input on Vdd.

    32

    SummarySummaryThere are a variety boards that may be usedThere are a variety boards that may be used

    with the BASIC Stamp.with the BASIC Stamp.

    Each has advantages and disadvantages.Each has advantages and disadvantages.Choosing the best choice based on featuresChoosing the best choice based on featuresand cost is important.and cost is important.

  • 8/7/2019 Bs 2 Tutorial

    17/188

    33

    End of Section 2End of Section 2

    34

    Section 3: BASIC Stamp Editor Section 3: BASIC Stamp Editor BASIC Stamp Editor BASIC Stamp Editor Identifying the BASIC StampIdentifying the BASIC StampWriting the ProgramWriting the ProgramDownloading or Running CodeDownloading or Running CodeTokenizing and ErrorsTokenizing and ErrorsCommenting CodeCommenting CodeDEBUG WindowDEBUG WindowMemory MapMemory MapPreferencesPreferencesHelp FilesHelp Files

    Instruction Syntax ConventionInstruction Syntax Convention

  • 8/7/2019 Bs 2 Tutorial

    18/188

    35

    BASIC Stamp Editor BASIC Stamp Editor The BASIC Stamp Editor is the application that isThe BASIC Stamp Editor is the application that isused to write, edit, and download the PBASICused to write, edit, and download the PBASICprograms for the BASIC Stamp.programs for the BASIC Stamp.

    The software may be downloaded for free fromThe software may be downloaded for free fromParallaxParallax . Some installations of Windows 95 and. Some installations of Windows 95 and98 may require an additional file to be installed.98 may require an additional file to be installed.Please see the information on the download pagePlease see the information on the download pagefor more information.for more information.

    Once installed, the Stamp Editor will be availableOnce installed, the Stamp Editor will be availableon your desktop, and as a menu option under on your desktop, and as a menu option under StartStart Program FilesProgram Files Parallax IncParallax Inc

    36

    Identifying the BASIC StampIdentifying the BASIC Stamp

    Connect the BASIC StampConnect the BASIC Stampcarrier board to your carrier board to your computer with a serialcomputer with a serialcable.cable.

    Power-up your BASICPower-up your BASICStamp carrier board.Stamp carrier board.

    Use theUse the Identify Identify button tobutton toverify communications toverify communications toyour BASIC Stamp.your BASIC Stamp.

  • 8/7/2019 Bs 2 Tutorial

    19/188

    37

    Identification ErrorsIdentification Errors

    If the ID shows:If the ID shows:No Device TypeNo Device TypeNo LoopbackNo Loopback

    No EchoNo EchoIt usually means the BASIC Stamp is not connected properly to theIt usually means the BASIC Stamp is not connected properly to thecomputer with a serial cable.computer with a serial cable.

    Verify the carrier board is connected to the computer with a serialVerify the carrier board is connected to the computer with a serialcable, full-modem variety (not null-modem).cable, full-modem variety (not null-modem).

    If your computer has multipleIf your computer has multipleCOM ports, try another.COM ports, try another.

    If the COM port you are usingIf the COM port you are usingis not listed, try adding it tois not listed, try adding it tothe Stamp Editor usingthe Stamp Editor usingEditEdit PreferencesPreferences ..

    38

    If the ID shows:If the ID shows:No Device TypeNo Device TypeLoopback - YesLoopback - YesEcho YesEcho YesIt usually means the BASIC Stamp is connected, but itIt usually means the BASIC Stamp is connected, but ithas no power.has no power.

    Verify the carrier board has power supplied and the power Verify the carrier board has power supplied and the power light is on (if available).light is on (if available).

  • 8/7/2019 Bs 2 Tutorial

    20/188

    39

    If the COM port cannotIf the COM port cannotbe opened, it usually meansbe opened, it usually meansanother program has controlanother program has controlof the port.of the port.

    Close any applicationsClose any applicationswhich may be using the port,which may be using the port,including terminal programs,including terminal programs,dial-up programs, Palm Pilot programs, PC Anywhere,dial-up programs, Palm Pilot programs, PC Anywhere,StampPlot and other communication programs.StampPlot and other communication programs.

    If you cannot resolve the problem, if possible:If you cannot resolve the problem, if possible:Test another persons operational board on your computer usingTest another persons operational board on your computer usingtheir cable and yours.their cable and yours.Test your board on another computer, preferably one that had aTest your board on another computer, preferably one that had aworking BASIC Stamp.working BASIC Stamp.

    Contact Parallax support:Contact Parallax support: [email protected]@parallax.com

    40

    Writing the ProgramWriting the Program

    BASIC Stamp programsBASIC Stamp programsare written in a version of are written in a version of BASIC called PBASICBASIC called PBASICentered into the BASICentered into the BASICStamp Editor.Stamp Editor.

    A program typically readsA program typically readsinputs, processing data,inputs, processing data,and controls outputs.and controls outputs.

    Programs must conformPrograms must conformto the rules of syntax soto the rules of syntax sothat the BASIC Stampthat the BASIC Stamp

    can understand what youcan understand what youare telling it.are telling it.

    DEBUG Hello World

  • 8/7/2019 Bs 2 Tutorial

    21/188

    41

    Once a program is entered, the RunOnce a program is entered, the Runbutton (or Ctrl-R) is used to tokenizebutton (or Ctrl-R) is used to tokenizeand download the program to theand download the program to theBASIC Stamp.BASIC Stamp.

    Downloading or Running CodeDownloading or Running Code

    The Editor will request youThe Editor will request youindicate the style of BASICindicate the style of BASICStamp you are using.Stamp you are using.

    The style may be selected from theThe style may be selected from themenu, or by selecting your color of menu, or by selecting your color of your BASIC Stamp on the button bar.your BASIC Stamp on the button bar.

    DEBUG Hello World{$STAMP BS2}DEBUG Hello World

    AA directivedirective will be added to the top of will be added to the top of your code.your code.

    42

    Tokenizing and ErrorsTokenizing and Errors

    If there are errors:If there are errors:An error message will appear indicating aAn error message will appear indicating aproblem, the status turnsproblem, the status turns redred and code isand code ishighlighted.highlighted.Generally, the error can be found byGenerally, the error can be found bylooking before the highlighted area.looking before the highlighted area.Read your code carefully looking for theRead your code carefully looking for thesyntax error syntax error or or bug bug . In this example. In this exampleDEBUG is incorrectly spelled.DEBUG is incorrectly spelled.

    Code may be syntax checked withoutCode may be syntax checked withoutdownloading by using the Syntax Checkdownloading by using the Syntax Checkbutton.button.

    When a program is Ran the PBASIC code is converted to symbolicWhen a program is Ran the PBASIC code is converted to symbolicformat called tokens. These are stored in ROM memory on your format called tokens. These are stored in ROM memory on your BASIC Stamp.BASIC Stamp.

    In order to tokenize your program, the code must to conform to theIn order to tokenize your program, the code must to conform to therules of syntax for the language.rules of syntax for the language.

  • 8/7/2019 Bs 2 Tutorial

    22/188

    43

    Commenting CodeCommenting CodeComments, or remarks, are descriptions or Comments, or remarks, are descriptions or explanations the programmer puts in the code toexplanations the programmer puts in the code toclarify what it is doing.clarify what it is doing.

    Comments are signified by leading with anComments are signified by leading with anapostrophe.apostrophe.

    Comments are NOTComments are NOTsyntax checked, nor syntax checked, nor do they increase thedo they increase thesize of your program.size of your program.So comment oftenSo comment oftenand at length!and at length!

    44

    DEBUG WindowDEBUG Window

    Programs may contain aPrograms may contain aDEBUG instruction. ThisDEBUG instruction. Thisinstruction sends serial datainstruction sends serial databack to the computer on theback to the computer on theserial cable.serial cable.

    When DEBUG is present in aWhen DEBUG is present in aprogram, a DEBUG window willprogram, a DEBUG window willopen in the Editor to view theopen in the Editor to view thereturning data.returning data.

    The DEBUG button may beThe DEBUG button may beused to manually open aused to manually open aDEBUG window.DEBUG window.

  • 8/7/2019 Bs 2 Tutorial

    23/188

    45

    Memory MapMemory Map

    The Memory Map button will open the BASIC StampThe Memory Map button will open the BASIC Stampwindow.window.

    This window shows how program (EEPROM) and variableThis window shows how program (EEPROM) and variablememory (RAM) is being utilized.memory (RAM) is being utilized.Note that the program is stored in memory from bottom-up.Note that the program is stored in memory from bottom-up.

    EEPROM Memory:EEPROM Memory:Program space of Program space of tokenized programtokenized program

    RAM Memory:RAM Memory:VariablesVariables

    RAM Memory:RAM Memory:I/O ControlI/O Control

    46

    PreferencesPreferencesUnder the Preferences button you may:Under the Preferences button you may:

    Change color, font, and tab spacing for the text editor Change color, font, and tab spacing for the text editor

    and debug screen.and debug screen.

    Set the COM port on whichSet the COM port on whichthe stamp is connected to, or the stamp is connected to, or be in automatic detection mode.be in automatic detection mode.

    Modify the DEBUGModify the DEBUGsettings.settings.

    You are encouraged toYou are encouraged tolook through the availablelook through the availablesettings to become familiar settings to become familiar

    with them.with them.

  • 8/7/2019 Bs 2 Tutorial

    24/188

    47

    Help FilesHelp FilesThere exists a help file that isThere exists a help file that isvery thorough at assistingvery thorough at assistingyou with any problems or you with any problems or questions you might havequestions you might haveabout instruction syntax or about instruction syntax or use while programming.use while programming.

    By highlighting an instructionBy highlighting an instructionand pressingand pressing F1F1 , the help, the helpfiles will open to displayfiles will open to displayinformation on thatinformation on thatinstruction.instruction.

    Help provides a description,Help provides a description,syntax (format) and examplesyntax (format) and examplefor each instruction.for each instruction.

    48

    Instruction Syntax ConventionInstruction Syntax Convention

    BASIC Stamp instructions follow a common codeBASIC Stamp instructions follow a common codeconvention for parameters (parts) of instructions.convention for parameters (parts) of instructions.

    Take for example the FREQOUT instructions, which mayTake for example the FREQOUT instructions, which maybe used to generate tones from a speaker:be used to generate tones from a speaker:FREQOUTFREQOUT Pin, Period, Freq1 {, Freq2}Pin, Period, Freq1 {, Freq2}

    The instruction requires that theThe instruction requires that the PinPin ,, Period Period , and, and Freq1Freq1 is suppliedis suppliedand that each are separated by commas.and that each are separated by commas.Optionally, the user MAY provideOptionally, the user MAY provide Freq2 Freq2 indicated by braces { }.indicated by braces { }.

    While PBASIC is NOT case-sensitive, the commonWhile PBASIC is NOT case-sensitive, the commonconvention is to capitalize instructions, and use 1convention is to capitalize instructions, and use 1 stst letter letter upper-case for all other code.upper-case for all other code.

  • 8/7/2019 Bs 2 Tutorial

    25/188

    49

    SummarySummaryThe BASIC Stamp Editor is an IDEThe BASIC Stamp Editor is an IDE(Integrated Development Environment) for:(Integrated Development Environment) for:

    Hardware identification.Hardware identification.Coding of the program.Coding of the program.Syntax (language rules) checking.Syntax (language rules) checking.Memory utilization reporting.Memory utilization reporting.Tokenizing and program transfer.Tokenizing and program transfer.Integrated instruction help.Integrated instruction help.

    50

    End of Section 3End of Section 3

  • 8/7/2019 Bs 2 Tutorial

    26/188

    51

    Section 4: Input, Output, and ProcessingSection 4: Input, Output, and ProcessingUsage NotesUsage NotesBefore Changing HardwareBefore Changing HardwareInputs, Processing, and OutputsInputs, Processing, and OutputsStamp I/OStamp I/O

    Output - Connecting an LEDOutput - Connecting an LEDBlinking the LED with HIGH, LOWBlinking the LED with HIGH, LOWBlinking the LED with OUTPUT and OUTBlinking the LED with OUTPUT and OUT

    DebuggingDebuggingDEBUG InstructionDEBUG InstructionDEBUG for Program Flow InformationDEBUG for Program Flow InformationUsing DEBUG ? to Display StatusUsing DEBUG ? to Display Status

    Digital InputsDigital InputsConnecting an Active-Low SwitchConnecting an Active-Low SwitchReading the SwitchReading the Switch

    Controlling Outputs with InputsControlling Outputs with InputsDIRS, INS, OUTSDIRS, INS, OUTSReading Analog Values with RCTimeReading Analog Values with RCTimeFrequency OutputFrequency Output

    52

    Usage NotesUsage NotesThis section is used to teach principles andThis section is used to teach principles and

    construct a basic circuit.construct a basic circuit.

    By the end of this section a complete circuitBy the end of this section a complete circuitwill be constructed consisting of 2 LEDs, 2will be constructed consisting of 2 LEDs, 2switches, a speaker and an RC network.switches, a speaker and an RC network.

    This circuit is also used in sections 5, 6 andThis circuit is also used in sections 5, 6 and7.7.

  • 8/7/2019 Bs 2 Tutorial

    27/188

    53

    Before Changing HardwareBefore Changing HardwareBefore you modify the hardware connected to theBefore you modify the hardware connected to theBASIC Stamp, it is best to download a simpleBASIC Stamp, it is best to download a simpleprogram.program.

    This prevents the new hardware from applyingThis prevents the new hardware from applyingvoltages which may cause damage to pinsvoltages which may cause damage to pinsconfigured for other hardware.configured for other hardware.

    Download the following program to the BASICDownload the following program to the BASICStamp:Stamp:

    DEBUG "HELLO WORLD!"

    54

    Inputs, Processing, and OutputsInputs, Processing, and OutputsAny system or program accepts input, processAny system or program accepts input, processinformation, and controls outputs.information, and controls outputs.

    The BASIC Stamp, and other microcontrollers,The BASIC Stamp, and other microcontrollers,specialize in using input devices such as switches,specialize in using input devices such as switches,and controlling output devices such as LEDs (Lightand controlling output devices such as LEDs (LightEmitting Diodes).Emitting Diodes).

    A program, written in a form of the BASICA program, written in a form of the BASIClanguage calledlanguage called PBASIC PBASIC , is used for processing by, is used for processing bywriting code that instructs the BS2 what actions towriting code that instructs the BS2 what actions totake.take.

    Processing OutputInput

  • 8/7/2019 Bs 2 Tutorial

    28/188

    55

    Stamp I/OStamp I/OThere are 16 I/O (Input/Output) pins on the BS2There are 16 I/O (Input/Output) pins on the BS2labeled P0 to P15. These are the pins throughlabeled P0 to P15. These are the pins throughwhich input and output devices may be connected.which input and output devices may be connected.

    Depending on the code that is written, each pinDepending on the code that is written, each pinmay act as an input to read a device, or as anmay act as an input to read a device, or as anoutput to control a device.output to control a device.

    We will begin by using a very common and simpleWe will begin by using a very common and simpleoutput device -- the LED.output device -- the LED.

    56

    Output - Connecting an LEDOutput - Connecting an LED

    Connect an LED to P8 as shown:Connect an LED to P8 as shown:

    In this configuration a LOW, or 0V, at P8 will allow current toIn this configuration a LOW, or 0V, at P8 will allow current toflow through the LED to Vdd (+5V) lighting it. When P8 is HIGHflow through the LED to Vdd (+5V) lighting it. When P8 is HIGH(+5V), no current will flow and the LED will not light. The LED is(+5V), no current will flow and the LED will not light. The LED isActive Low.Active Low.

    An LED is a diode, meaning electrons can flow inonly one direction, so polarity is important. The LEDshould have a flat side indicating the cathode or negative terminal. Also, the anode (positiveterminal) generally has a longer lead than thecathode .

    Connected on P8.Angle of shotmakes it appear to be on P9.

    Vdd, NOT Vin.

    Note cathode:the flat side of LED

    220 ohm = RED RED BROWN GOLD

  • 8/7/2019 Bs 2 Tutorial

    29/188

    57

    Another configuration that could be used is to have theAnother configuration that could be used is to have theLEDLED Active-HighActive-High . In this configuration the LED will light. In this configuration the LED will lightwhen the output is HIGH, or +5V. Current flows fromwhen the output is HIGH, or +5V. Current flows from

    ground or Vss (0V) to the 5V output on P8.ground or Vss (0V) to the 5V output on P8.

    Do NOT build this circuit, it is for information only. TheDo NOT build this circuit, it is for information only. Thecircuit on the previous slide should be constructed.circuit on the previous slide should be constructed.

    The 220 resistor will limit current flow toapproximately 20mA . The output currentfrom a BS2 pin should be limited to 20mAmaximum. The maximum current for anLED is generally 30mA.

    58

    Blinking the LED with HIGH, LOWBlinking the LED with HIGH, LOWUse the Stamp Editor to enter the following program:Use the Stamp Editor to enter the following program:

    Download or run the program.Download or run the program.

    Monitor the LED. It should blink at a rate of 1 second OFF,Monitor the LED. It should blink at a rate of 1 second OFF,5 seconds ON. If not, check your configuration and code.5 seconds ON. If not, check your configuration and code.

    Prog 4A: Blink LED program

    Main:HIGH 8 'Turn off LEDPAUSE 1000 'Wait 1 secondLOW 8 'Turn on LEDPAUSE 5000 'Wait 5 seconds

    GOTO Main 'Jump back to beginning

  • 8/7/2019 Bs 2 Tutorial

    30/188

    59

    Code DiscussionCode DiscussionHIGH defines the pin to be an output and sets it to a HIGH state, digitalHIGH defines the pin to be an output and sets it to a HIGH state, digital1 or 5V.1 or 5V.

    HIGHHIGH pin 0-15 pin 0-15 HIGH 8HIGH 8

    LOW defines the pin to be an output and sets it to a LOW state, digitalLOW defines the pin to be an output and sets it to a LOW state, digital0 or 0V.0 or 0V.

    LOWLOW pin 0-15 pin 0-15 LOW 8LOW 8

    PAUSE instructs the BS2 to wait for the defined number of PAUSE instructs the BS2 to wait for the defined number of milliseconds (1/1000 seconds).milliseconds (1/1000 seconds).

    PAUSEPAUSE time in milliseconds 0-65535 time in milliseconds 0-65535 PAUSE 1000PAUSE 1000

    GOTO instructs the BS2 to jump to the defined label. More about thisGOTO instructs the BS2 to jump to the defined label. More about thiswill be covered in Programming Structures.will be covered in Programming Structures.

    GOTOGOTO Label Label

    60

    Blinking the LED with OUTPUT and OUTBlinking the LED with OUTPUT and OUT

    The HIGH and LOW instructions perform 2 actions:The HIGH and LOW instructions perform 2 actions:

    Sets direction of the I/O pin to an output.Sets direction of the I/O pin to an output.Sets the state of the output to be 0 or 1 (0V or 5V)Sets the state of the output to be 0 or 1 (0V or 5V)

    Another means to perform the same process is toAnother means to perform the same process is touse code to set the direction, then the state.use code to set the direction, then the state.

    Enter and run this example.Enter and run this example.' Prog 4B: Blink LED program using OUTPUT and OUT

    OUTPUT 8 'Set P8 to be an outputMain:

    OUT8 = 1 'Turn off LED1PAUSE 1000 'Wait 1 second

    OUT8 = 0 'Turn on LED1PAUSE 5000 'Wait 5 secondsGOTO Main 'Jump back to beginning

  • 8/7/2019 Bs 2 Tutorial

    31/188

    61

    Code DiscussionCode DiscussionOUTPUT sets the pin to act as an output.OUTPUT sets the pin to act as an output.

    OUTPUTOUTPUT pinpinOUTPUT 8OUTPUT 8

    The BS2 on startup sets all I/O pins to inputs.The BS2 on startup sets all I/O pins to inputs.

    OUT sets the state of the output.OUT sets the state of the output.OUTpin =OUTpin = 1 or 0 1 or 0 OUT8 = 1OUT8 = 11 sets the output HIGH (5V Digital High or 1).1 sets the output HIGH (5V Digital High or 1).0 sets the output LOW (0V Digital Low or 0).0 sets the output LOW (0V Digital Low or 0).

    Depending on program need, sometimes it is better to useDepending on program need, sometimes it is better to usethe HIGH and LOW instructions, and other times to usethe HIGH and LOW instructions, and other times to useOUTPUT and OUT.OUTPUT and OUT.

    62

    Challenge 4A: Blink a 2Challenge 4A: Blink a 2 ndnd LEDLED1.1. Connect a secondConnect a second active-low active-low LED onLED on

    P9.P9.

    2.2. Code a program to blink only this LEDCode a program to blink only this LEDusing HIGH and LOW instructions.using HIGH and LOW instructions.

    3.3. Code a program to blink only this LEDCode a program to blink only this LEDusing OUTPUT and OUT instructions.using OUTPUT and OUT instructions.

    SolutionSolution

    SolutionSolution

    SolutionSolution

  • 8/7/2019 Bs 2 Tutorial

    32/188

    63

    Challenge 4B: LED CyclingChallenge 4B: LED CyclingCode a program to perform the following sequenceCode a program to perform the following sequence(use HIGH and LOW):(use HIGH and LOW):

    LED1 on P8 ON, LED2 on P9 OFFLED1 on P8 ON, LED2 on P9 OFFWait 2 secondsWait 2 secondsLED1 on P8 ON, LED2 on P9 ONLED1 on P8 ON, LED2 on P9 ONWait 1 secondWait 1 secondBoth LEDs OFFBoth LEDs OFFWait one-half secondWait one-half secondRepeatRepeat

    SolutionSolution

    64

    DebuggingDebuggingDebugging refers to the act of finding errors in code andDebugging refers to the act of finding errors in code andcorrecting them. There are 2 types of errors which can becorrecting them. There are 2 types of errors which can be

    made when coding:made when coding: Syntax errorsSyntax errors andand Logical errorsLogical errors ..

    Syntax errorsSyntax errors are those that occur when theare those that occur when theeditor/compiler does not understand the code written.editor/compiler does not understand the code written.

    An example would be: GO TO MainAn example would be: GO TO MainThe PBASIC tokenizer, which takes our code and puts itThe PBASIC tokenizer, which takes our code and puts itin a form the BS2 understands, does not have anin a form the BS2 understands, does not have aninstruction called GO TO (it has one called GOTO).instruction called GO TO (it has one called GOTO).

    This section of code would be flagged as having aThis section of code would be flagged as having a

    syntax problem, which we identify and correct.syntax problem, which we identify and correct.

  • 8/7/2019 Bs 2 Tutorial

    33/188

    65

    Logical errorsLogical errors are those which have a validare those which have a validsyntax, but fail to perform the action we desire.syntax, but fail to perform the action we desire.

    For example, our program runs, but it seems theFor example, our program runs, but it seems theLED is off an abnormally long time. Looking at theLED is off an abnormally long time. Looking at thecode we find the bug:code we find the bug:PAUSE 50000PAUSE 50000 instead of instead of PAUSE 5000PAUSE 5000 ..

    The PBASIC compiler was perfectly happy with aThe PBASIC compiler was perfectly happy with a50 second pause, but logically it was not what we50 second pause, but logically it was not what wewanted to happen.wanted to happen.

    Syntax errors are easily flagged when we try to runSyntax errors are easily flagged when we try to runthe program. Logical errors are more difficultthe program. Logical errors are more difficultbecause they require the programmer to analyze thebecause they require the programmer to analyze thecode and what is occurring to determine the bug.code and what is occurring to determine the bug.

    66

    DEBUG InstructionDEBUG InstructionThe DEBUG instruction provides a valuable toolThe DEBUG instruction provides a valuable toolfor the programmer.for the programmer.

    It provides a means of real-time feedback inIt provides a means of real-time feedback indebugging to:debugging to:

    Observe program execution.Observe program execution.Observe program values.Observe program values.

    It also allows the programmer to use a veryIt also allows the programmer to use a verysophisticated output device A computer monitor.sophisticated output device A computer monitor.

    When a DEBUG instruction used, the StampWhen a DEBUG instruction used, the Stamp

    Editors DEBUG window will open and display theEditors DEBUG window will open and display thedata.data.

  • 8/7/2019 Bs 2 Tutorial

    34/188

    67

    When we run, or download, a program to the BS2,When we run, or download, a program to the BS2,the program is transferred serially from Stampthe program is transferred serially from StampEditor though a serial COM port to the BASICEditor though a serial COM port to the BASICStamp.Stamp.

    Using the same serial connection, the BS2 canUsing the same serial connection, the BS2 cantransfer data back to the Stamp Editor to betransfer data back to the Stamp Editor to bedisplayed.displayed.

    Throughout this tutorial we will use DEBUG for Throughout this tutorial we will use DEBUG for various indications and describe the syntax used.various indications and describe the syntax used.

    68

    DEBUG for Program Flow InformationDEBUG for Program Flow Information

    Sometimes it is difficult to analyze a problem in theSometimes it is difficult to analyze a problem in thecode because we have no indication where in thecode because we have no indication where in theprogram the BS2 is currently at. A simple DEBUGprogram the BS2 is currently at. A simple DEBUGin the code can provide feedback as to flow.in the code can provide feedback as to flow.

    DEBUG A description of code to be performed,CRDEBUG A description of code to be performed,CRCR is short for carriage return to move the cursor to theCR is short for carriage return to move the cursor to thenext line.next line.

    DEBUG could be used to help identify the bugDEBUG could be used to help identify the bugwhere 50000 was typed instead of 5000.where 50000 was typed instead of 5000.

  • 8/7/2019 Bs 2 Tutorial

    35/188

    69

    By placing some key DEBUG statements, we can observeBy placing some key DEBUG statements, we can observethe flow of the program. Of course, in most cases you maythe flow of the program. Of course, in most cases you maywant to only place a DEBUG in the most likely areas basedwant to only place a DEBUG in the most likely areas based

    on observation.on observation.'Prog 4C: Blink LED program with DEBUG location

    OUTPUT 8 'Set P8 to outputMain: DEBUG " Turn Off LED",CR

    OUT8 = 1 'Turn off LED DEBUG " Wait 1 second",CR

    PAUSE 1000 'Wait 1 second DEBUG " Turn Off LED",CR

    OUT8 = 0 'Turn on LED DEBUG " Wait 5 seconds",CR

    PAUSE 50000 'Wait 5 seconds DEBUG " Go repeat program",CRGOTO Main 'Jump back to beginning

    70

    Using DEBUG ? to Display StatusUsing DEBUG ? to Display StatusAnother simple use of DEBUG is to indicate the status of Another simple use of DEBUG is to indicate the status of an output or input.an output or input.

    DEBUG ? OUTpinDEBUG ? OUTpin

    Say for example the P8 LED was not lighting. Is it a codeSay for example the P8 LED was not lighting. Is it a codeproblem (OUT8 not going low?) or an electronics problemproblem (OUT8 not going low?) or an electronics problem(LED in backwards?).(LED in backwards?).

    Using DEBUG inUsing DEBUG inkey spots, the statuskey spots, the statusof P8 can be verified.of P8 can be verified.

    'Prog 4D: Blink LED program with DEBUGvalue

    Main:HIGH 8 'Turn off LED1

    DEBUG ? OUT8 PAUSE 1000 'Wait 1 second

    LOW 8 'Turn on LED1DEBUG ? OUT8

    PAUSE 5000 'Wait 5 secondsGOTO Main 'Jump back to beginning

  • 8/7/2019 Bs 2 Tutorial

    36/188

    71

    Challenge 4C: DebuggingChallenge 4C: DebuggingModify the code from Challenge 4B to indicate the status of Modify the code from Challenge 4B to indicate the status of P8 and P9 and describe the number of seconds of theP8 and P9 and describe the number of seconds of thepause.pause.

    Example output:Example output:

    SolutionSolution

    72

    Digital InputsDigital InputsJust as P0 P15 on the BASIC Stamp can act asJust as P0 P15 on the BASIC Stamp can act asoutputs to control devices, they can act as inputsoutputs to control devices, they can act as inputsto read devices, such as switches.to read devices, such as switches.

    By default, the BASIC Stamp I/O pins will act asBy default, the BASIC Stamp I/O pins will act asinputs unless specifically set to be an output. Ininputs unless specifically set to be an output. Inour code we specify the I/O as inputs out of goodour code we specify the I/O as inputs out of goodprogramming habits.programming habits.

    INPUT pinINPUT pinINPUT 10INPUT 10

  • 8/7/2019 Bs 2 Tutorial

    37/188

    73

    Connecting an Active-Low SwitchConnecting an Active-Low SwitchConnect a push-button switch to P10 as shown:Connect a push-button switch to P10 as shown:

    The push-buttons used in thistutorial have 4 terminals. 2 areelectrically connected on one side of the button, and the other 2 on theother side. By wiring to opposingcorners we ensure the proper connection independent of buttonrotation.

    Button alone

    The push-button is a momentary normally-The push-button is a momentary normally-open (N.O.) switch. When the button IS NOTopen (N.O.) switch. When the button IS NOTpressed (open), P10 will sense Vdd (5V,pressed (open), P10 will sense Vdd (5V,HIGH, 1) because it isHIGH, 1) because it is pulled-uppulled-up to Vdd.to Vdd.

    When PB1 IS pressed (closed), P10 will senseWhen PB1 IS pressed (closed), P10 will sense

    Vss (0V, LOW, 0) making itVss (0V, LOW, 0) making it Active-LowActive-Low ..

    1K = Brown Black Red Gold

    74

    Active-High Push-Button SwitchActive-High Push-Button SwitchAnother configuration that could have been used is shownAnother configuration that could have been used is shownhere. Notice that the position of the switch and resistor here. Notice that the position of the switch and resistor

    have been reversed.have been reversed.When the button IS NOT pressed (open), P10 will sense Vss (0V,When the button IS NOT pressed (open), P10 will sense Vss (0V,LOW, 0) because it isLOW, 0) because it is pulled-downpulled-down to Vss.to Vss.When PB1 IS pressed (closed), P10 will sense VddWhen PB1 IS pressed (closed), P10 will sense Vdd(5V, HIGH, 1) making it(5V, HIGH, 1) making it Active-HighActive-High ..

    Do NOT build this circuit, it is for information only. TheDo NOT build this circuit, it is for information only. Thecircuit on the previous slide should be constructed.circuit on the previous slide should be constructed.

    The BASIC Stamp has uncommitted inputs. Thatis, when an I/O pin is not connected and acting asan input, it cannot be assured to be either HIGHor LOW. Pull-up and pull-down resistors areneeded to commit the input to the non-active(open) state for switches.

    The 1K resistor is used to prevent a short-circuitbetween Vdd and Vss when the switch is closed.

  • 8/7/2019 Bs 2 Tutorial

    38/188

    75

    Reading the SwitchReading the SwitchThe digital value of an input can be read using theThe digital value of an input can be read using the INpinINpin instruction.instruction.

    A 1 or 0 will be returned indicating a HIGH or LOW stateA 1 or 0 will be returned indicating a HIGH or LOW state

    on the input.on the input.

    This program uses DEBUG to display the digital value.This program uses DEBUG to display the digital value.Enter and Run the program. Note the value displayedEnter and Run the program. Note the value displayedwhen the push-button is in the down and up states.when the push-button is in the down and up states.

    'Prog 4E: Display the status of PB1 on P10

    INPUT 10 'Set P10 to be an input

    Main:DEBUG ? IN10 'Display status of P10PAUSE 500 'Short pause

    GOTO Main 'Jump back to beginning

    76

    Challenge 4D: Reading a 2Challenge 4D: Reading a 2 ndnd ButtonButton

    1.1. Add a second active-low push-buttonAdd a second active-low push-buttonswitch on P11.switch on P11.

    2.2. Code a program to display the status of Code a program to display the status of only PB2 on P11.only PB2 on P11.

    3.3. Code a program to display the status of Code a program to display the status of BOTH switches.BOTH switches.

    SolutionSolution

    SolutionSolution

    SolutionSolution

  • 8/7/2019 Bs 2 Tutorial

    39/188

    77

    Controlling Outputs with InputsControlling Outputs with InputsNow that we can control outputs and read inputs, it's timeNow that we can control outputs and read inputs, it's timeto perform a little processing and put the pieces together.to perform a little processing and put the pieces together.

    The state of an input may be read withThe state of an input may be read with INpi INpi n.n.

    The state of an output may be controlled withThe state of an output may be controlled with OUTpinOUTpin ..

    Here is a program that will use the input pushbutton PB1Here is a program that will use the input pushbutton PB1on P10 to control output LED1 on P8.on P10 to control output LED1 on P8.'Prog 4F: Controlling LED1 with input PB1

    INPUT 10 'Set P10 to be an inputOUTPUT 8 'Set P8 to be an output

    Main:OUT8 = IN10 'Set LED1 = PB1

    GOTO Main 'Jump back to beginning

    78

    Challenge 4E: Switch & LED ControlChallenge 4E: Switch & LED Control1.1. Code a program that will controlCode a program that will control

    LED2 on P9 with PB2 on P11.LED2 on P9 with PB2 on P11.

    2.2. Code a program that will control:Code a program that will control:LED1 on P8 with PB2 on P11LED1 on P8 with PB2 on P11LED2 on P9 with PB1 on P10LED2 on P9 with PB1 on P10

    3.3. Code a program that will control:Code a program that will control:LED1 and LED 2 on P8 and P9 withLED1 and LED 2 on P8 and P9 withbutton PB1 on P10.button PB1 on P10.

    SolutionSolution

    SolutionSolution

    SolutionSolution

  • 8/7/2019 Bs 2 Tutorial

    40/188

    79

    DIRS, INS, OUTSDIRS, INS, OUTSUp to this point I/O have been set as inputs or Up to this point I/O have been set as inputs or outputs, and states set or read individually.outputs, and states set or read individually.

    Looking at the Memory Map, there areLooking at the Memory Map, there are3 16-bit registers which set the3 16-bit registers which set thedirection for the I/O, and which aredirection for the I/O, and which areread or written to.read or written to.

    OUTPUT 8OUTPUT 8 sets bit 8 (P8) for sets bit 8 (P8) for output in the DIRS register.output in the DIRS register.

    This may also be written asThis may also be written asDIR8=1DIR8=1 (1=output, 0 = input).(1=output, 0 = input).

    OUT9 =1OUT9 =1 sets the output state insets the output state inthe OUTS register for bit 9 (P9).the OUTS register for bit 9 (P9).

    IN10IN10 reads the value in the 10reads the value in the 10 thth bitbit(P10) of INS.(P10) of INS.

    Note: The colors of theseregisters are not affected by thecode.

    80

    The I/O can also be addressed as nibbles,The I/O can also be addressed as nibbles,

    bytes or the entire word.bytes or the entire word. IN0OUT0DIR0

    IN15OUT15DIR15

    TO As BITS

    INDOUTDDIRD

    INCOUTCDIRC

    INBOUTBDIRB

    INAOUTADIRA

    AsNIBBLES

    (High Byte)INH

    OUTHDIRH

    (Low Byte)INL

    OUTLDIRL

    AsBYTES

    INS

    OUTSDIRS

    As 16-BitWORDS

  • 8/7/2019 Bs 2 Tutorial

    41/188

    81

    In our circuit, there are output devices on P8 andIn our circuit, there are output devices on P8 andP9, and input devices on P10 and P11. P8 P11P9, and input devices on P10 and P11. P8 P11make up nibble C.make up nibble C.

    The direction of the I/O can be set as a nibbleThe direction of the I/O can be set as a nibblewith:with:DIRC = %0011DIRC = %0011 in binary. It may also be written asin binary. It may also be written asDIRC = 3DIRC = 3 in decimal, but the binary form is muchin decimal, but the binary form is mucheasier to read for determining individual bit states.easier to read for determining individual bit states.

    This will set the DIRS nibble C for input (P11), inputThis will set the DIRS nibble C for input (P11), input(P10), output (P9), output (P8).(P10), output (P9), output (P8).Note that the bit positions are most-significant bit (MSB)Note that the bit positions are most-significant bit (MSB)to least-significant bit (LSB).to least-significant bit (LSB).

    82

    Some various examples to illustrate the flexibility, codeSome various examples to illustrate the flexibility, codesavings, and increased speed possibilities:savings, and increased speed possibilities:

    To read the entire lower byte (P0-P7) as inputs:To read the entire lower byte (P0-P7) as inputs:DIRL=%00000000DIRL=%00000000X = INLX = INL

    To count up in binary on 8 LEDs connected on P8 toTo count up in binary on 8 LEDs connected on P8 toP15:P15:DIRH = %11111111DIRH = %11111111FOR X = 0 to 255FOR X = 0 to 255

    OUTH = XOUTH = XNEXTNEXT

    To set 4 outputs on P4-P7 equal to 4 inputs onTo set 4 outputs on P4-P7 equal to 4 inputs onP12-P15:P12-P15:DIRS = %0000000011110000DIRS = %0000000011110000OUTB = INDDOUTB = INDD

  • 8/7/2019 Bs 2 Tutorial

    42/188

    83

    Reading Analog Values with RCTimeReading Analog Values with RCTimeA very simple method of bringing analog data into theA very simple method of bringing analog data into theBASIC Stamp is through the use of an instruction calledBASIC Stamp is through the use of an instruction calledRCTime.RCTime.

    RCTime requires a capacitor and a resistor network, either RCTime requires a capacitor and a resistor network, either of which may be variable (adjustable). Common variableof which may be variable (adjustable). Common variableresistance devices include:resistance devices include:

    Variable-Turn Resistors (Potentiometers)Variable-Turn Resistors (Potentiometers)Photo-ResistorsPhoto-ResistorsTemperature sensing devices such as thermistorsTemperature sensing devices such as thermistors

    Using RCTime with any of these devices can provide real-Using RCTime with any of these devices can provide real-time analog data input.time analog data input.

    84

    Connecting the RC NetworkConnecting the RC NetworkConnect the Resistor-Capacitor (RC) network:Connect the Resistor-Capacitor (RC) network:

    RCTime measures the time to charge the capacitor

    through the resistor. The higher the resistance or capacitance, the longer the time. For a full discussionon RCTime, please see your editor help files or BASICStamp Manual.

    RC Network alone Full Circuit with RC Network

    Resistor, capacitor and center pin of potentiometer onsame row.

    You may also use a 1uF capacitor with a 10K ohmpotentiometer.

  • 8/7/2019 Bs 2 Tutorial

    43/188

    85

    RCTime CodeRCTime CodeEnter and run the following code.Enter and run the following code.

    Adjust the resistor full each direction and monitor the value. The fullAdjust the resistor full each direction and monitor the value. The fullrange should be approximately 0-6000.range should be approximately 0-6000.

    'Prog 4G: Monitoring RCTime

    Pot VAR WORD 'Variable to hold results

    Main:HIGH 7 'Discharge networkPAUSE 1 'Time to fully dischargeRCTIME 7,1,Pot 'Read charge time and store in PotDEBUG ? Pot 'Display value of PotPAUSE 500 'Short pause

    GOTO Main 'Jump back to beginning

    86

    RCTime Code DiscussionRCTime Code DiscussionPot VAR WORDPot VAR WORD defines a variable named Pot. Moredefines a variable named Pot. Moreabout variables will be discussed in the next section.about variables will be discussed in the next section.

    HIGH 7HIGH 7 places +5V on pin 7, discharging the capacitor.places +5V on pin 7, discharging the capacitor.

    PAUSE 1PAUSE 1 provides time to allow the capacitor to fullyprovides time to allow the capacitor to fullydischarge.discharge.

    RCTIME 7,1,PotRCTIME 7,1,Pot instructs the BS2 to time on pin 7 howinstructs the BS2 to time on pin 7 howlong it takes leave the specified state (1) and store thelong it takes leave the specified state (1) and store theresults into the variable Pot.results into the variable Pot.

    RCTIME pin, state, variableRCTIME pin, state, variable

  • 8/7/2019 Bs 2 Tutorial

    44/188

  • 8/7/2019 Bs 2 Tutorial

    45/188

    89

    Frequency OutputFrequency OutputThe PBASIC instruction FREQOUT can be used to easilyThe PBASIC instruction FREQOUT can be used to easilydrive a speaker for sound-effects.drive a speaker for sound-effects.Connect the components to the circuit.Connect the components to the circuit.

    NOTE: If you are using the BASIC StampActivity Board, the speaker is on P11.You will need to adjust the code used inthis part accordingly.

    90

    Frequency Output CodeFrequency Output CodeEnter and run the following code:Enter and run the following code:

    If all went well you should be hearing a tone.If all went well you should be hearing a tone.

    The syntax of FREQOUT is:The syntax of FREQOUT is:FREQOUTFREQOUT pin, duration in milliseconds, frequency in Hertz pin, duration in milliseconds, frequency in Hertz

    The allowable duration and frequency is 0 32767 thoughThe allowable duration and frequency is 0 32767 thoughyour speaker will only have decent tone generationyour speaker will only have decent tone generationbetween 500-4000Hz or so.between 500-4000Hz or so.

    'Prog 4G: Simple Frequency Generation

    'Activity Board -- use FREQOUT 11 for pin 11.

    Main:FREQOUT 1, 2000, 1000 'Tone at 1000Hz for 2 secondsPAUSE 1000 'Short pause

    GOTO Main 'Jump back to beginning

  • 8/7/2019 Bs 2 Tutorial

    46/188

    91

    Challenge 4F: Variable Frequency ControlChallenge 4F: Variable Frequency Control

    Combine what was learned in using RCTIME andCombine what was learned in using RCTIME andFREQOUT to code a program which changes theFREQOUT to code a program which changes thetone of the speaker in relation to the potentiometer tone of the speaker in relation to the potentiometer

    setting.setting.

    SolutionSolution

    HintHint

    92

    SummarySummaryThe BASIC Stamp can control simple output devices, suchThe BASIC Stamp can control simple output devices, suchas LEDs, with instructions such as HIGH, LOW and OUT.as LEDs, with instructions such as HIGH, LOW and OUT.

    The BASIC Stamp can read simple input devices, such asThe BASIC Stamp can read simple input devices, such asswitches, using the IN instruction.switches, using the IN instruction.

    Multiple I/O can be read or written to as grouping of bits.Multiple I/O can be read or written to as grouping of bits.

    Simple resistive analog values may be read using theSimple resistive analog values may be read using theRCTime instruction.RCTime instruction.

    Output frequency on a pin can be performed with theOutput frequency on a pin can be performed with theFREQOUT instruction.FREQOUT instruction.

  • 8/7/2019 Bs 2 Tutorial

    47/188

    93

    End of Section 4End of Section 4

    94

    Section 5: Variables and AliasesSection 5: Variables and AliasesVariablesVariables

    RAM MemoryRAM MemoryVariable TypesVariable TypesVariable DeclarationVariable DeclarationVariable ConventionsVariable ConventionsCoding with VariablesCoding with Variables

    ConstantsConstantsCoding with ConstantsCoding with Constants

    I/O AliasesI/O AliasesCoding using I/O AliasCoding using I/O AliasCommon Circuit Declar Common Circuit Declar

  • 8/7/2019 Bs 2 Tutorial

    48/188

    95

    Variables OverviewVariables OverviewVariables are needed when a program requires aVariables are needed when a program requires avalue to be stored.value to be stored.

    Variables correspond to a memory location whichVariables correspond to a memory location whichwe can read from and write to (Random Accesswe can read from and write to (Random AccessMemory RAM).Memory RAM).

    Variables allow the programmer to use descriptiveVariables allow the programmer to use descriptivewords to indicate the contents of the memorywords to indicate the contents of the memorylocation.location.

    Aliases may also be declared for I/O control toAliases may also be declared for I/O control toallow descriptive words to indicate deviceallow descriptive words to indicate device

    connections.connections.

    96

    RAM MemoryRAM MemoryOnce a program in entered, the Memory MapOnce a program in entered, the Memory Mapbutton on the toolbar may be clicked to view thebutton on the toolbar may be clicked to view thecontents of the code memory (EEPROM Map) andcontents of the code memory (EEPROM Map) andthe variable memory (RAM Map).the variable memory (RAM Map).

    In the BS2, the code spaceIn the BS2, the code spaceis 2K bytes (2048 bytes) inis 2K bytes (2048 bytes) insize and fills from thesize and fills from thebottom up.bottom up.

    The RAM for variableThe RAM for variablestorage is 26 bytes in size.storage is 26 bytes in size.

  • 8/7/2019 Bs 2 Tutorial

    49/188

    97

    INS, OUTS and DIRS are the registers (RAMINS, OUTS and DIRS are the registers (RAMlocations) which hold the status of the I/O pins.locations) which hold the status of the I/O pins.

    REG0 REG12 are 16-bit registers (word sized)REG0 REG12 are 16-bit registers (word sized)used for general variable storage.used for general variable storage.

    The variable registers may hold:The variable registers may hold:13 16-bit variables (Words)13 16-bit variables (Words)26 8-bit variables (Bytes)26 8-bit variables (Bytes)52 4-bit variables (Nibbles)52 4-bit variables (Nibbles)208 1-bit variables (Bits)208 1-bit variables (Bits)

    ORORAny combination of the aboveAny combination of the abovewithin memory size constraints.within memory size constraints.

    98

    A variable may be declared to be a word, byte, nibble or A variable may be declared to be a word, byte, nibble or bit. To maximize the limited memory, programmers usebit. To maximize the limited memory, programmers usethe smallest size that will meet the needs of the variablethe smallest size that will meet the needs of the variablerequirements.requirements.The maximum number of unique states (modulus) for eachThe maximum number of unique states (modulus) for eachsize is:size is: 22nn wherewhere nn is the number of bits.is the number of bits.i.e.: A byte, with 8 bits, has 2i.e.: A byte, with 8 bits, has 2 88 unique values or 256.unique values or 256.In binary, the maximum value for each size is:In binary, the maximum value for each size is:22 nn -1 where-1 where nn is the number of bits.is the number of bits.i.e.: A byte, with 8 bits, can hold 0 to 2i.e.: A byte, with 8 bits, can hold 0 to 2 88-1, or 0 to 255.-1, or 0 to 255.

    Variable TypesVariable Types

    0 to 65535 unsigned-32768 to +32767 signed

    0 to 255

    0 to 15

    0 or 1

    21616-bit Word2

    8

    Byte

    24Nibble (Nib)

    21Bit

  • 8/7/2019 Bs 2 Tutorial

    50/188

    99

    Variable DeclarationVariable DeclarationA variable in PBASIC is declared with the syntax of:A variable in PBASIC is declared with the syntax of:variableName VAR sizevariableName VAR size

    For example, the following will declare a variable namedFor example, the following will declare a variable namedTemperatureTemperature and allocate a byte of memory for it. This 8-and allocate a byte of memory for it. This 8-bit location can be used to hold values between 0 and 255.bit location can be used to hold values between 0 and 255.Temperature VAR BYTETemperature VAR BYTE

    'Prog 5A: Test of variable declaration

    ' *************** Declare VariablesTemperature VAR BYTEMy_Count VAR WORDSwitch1 VAR BITButtonNum VAR NIB

    Temperature = 100

    100

    Open the Memory Map to see how the RAM was allocatedOpen the Memory Map to see how the RAM was allocatedfor the various declarations:for the various declarations:

    My_Count16-bit Word

    Temperature8-bit Byte

    ButtonNum4-bit Nibble

    Switch11-bit

    Memory is allocated top tobottom, left to right fromlargest variables to smallestindependent of the order declared.

  • 8/7/2019 Bs 2 Tutorial

    51/188

    101

    Variables can be read and modified. Enter and run theVariables can be read and modified. Enter and run thefollowing code. Monitor the values of each as to when theyfollowing code. Monitor the values of each as to when theyoverflow the limits of their size.overflow the limits of their size.

    'Prog 5B: Test of variable sizes

    ' *********************** Declare VariablesByteCount VAR BYTEWordCount VAR WORDBitCount VAR BITNibCount VAR NIB

    Main:WordCount = WordCount + 1000 'Add to each variableByteCount = ByteCount + 20NibCount = NibCount + 1BitCount = BitCount + 1DEBUG CLS 'Clear the screenDEBUG ? WordCount : DEBUG ? ByteCount : DEBUG ? NibCount : DEBUG ? BitCountPAUSE 500

    GOTO Main

    Colons may be used to separate instructions on a single line

    102

    Variable ConventionsVariable ConventionsGood variable naming and commenting is important andGood variable naming and commenting is important andthere are certain rules in naming:there are certain rules in naming:

    Variables cannot contain special characters such as !,Variables cannot contain special characters such as !,@,$ except for an underscore, _.@,$ except for an underscore, _. My_VariableMy_VariableVariables may contain numbers but cannot start with aVariables may contain numbers but cannot start with anumber.number. Freq1Freq1Variable names cannot be a PBASIC instruction.Variable names cannot be a PBASIC instruction.Variables should have descriptive names. Generally,Variables should have descriptive names. Generally,capitalize the 1capitalize the 1 stst character of each word.character of each word. CountOfPressesCountOfPressesDeclare all variables at the top of your code andDeclare all variables at the top of your code andcomment their use.comment their use.Size the variable appropriate to its use conservingSize the variable appropriate to its use conservingmemory whenever possible.memory whenever possible.Re-use variables for common tasks such as multipleRe-use variables for common tasks such as multipleloops in the code.loops in the code.

  • 8/7/2019 Bs 2 Tutorial

    52/188

    103

    'Sample program with variables

    ' ****************** Declarations **************************' ****************** Variablesx VAR BYTE 'General use variablePressCount VAR WORD 'Holds number of times button is pressedPot_Value VAR WORD 'Value of Pot from RCTIMESwitch1 VAR BIT 'Value of switch 1

    All the variables in the above code fragment are legally named andAll the variables in the above code fragment are legally named andfollow good convention.follow good convention.

    Examples of illegal variable names:Examples of illegal variable names:My CountMy Count Space in nameSpace in name1Switch1Switch Starts with a valueStarts with a valueStop!Stop! Invalid name character Invalid name character CountCount PBASIC instructionPBASIC instruction

    Due to space constraints, the tutorial examples may be briefer inDue to space constraints, the tutorial examples may be briefer in

    commenting than good practice dictates.commenting than good practice dictates.

    104

    Challenge 5A: Variable NamingChallenge 5A: Variable NamingDeclare variables for the following requirements:Declare variables for the following requirements:

    To hold the number of seconds in a minute.To hold the number of seconds in a minute.

    To hold the number of dogs in a litter.To hold the number of dogs in a litter.

    To hold the count of cars in a 50 car garage.To hold the count of cars in a 50 car garage.

    To hold the status of an output.To hold the status of an output.

    To hold the indoor temperature.To hold the indoor temperature.

    To hold the temperature of a kitchen oven.To hold the temperature of a kitchen oven.

    SolutionSolution

  • 8/7/2019 Bs 2 Tutorial

    53/188

    105

    Coding with VariablesCoding with VariablesTo assign a variable a value, an equation sets it equal to a value:To assign a variable a value, an equation sets it equal to a value:VariableName = valueVariableName = value

    Once assigned a value, variables may be used in place of values for Once assigned a value, variables may be used in place of values for any number of purposes.any number of purposes.

    Enter and test this program by slowly and quickly adjusting theEnter and test this program by slowly and quickly adjusting thepotentiometer.potentiometer.

    'Prog 5C: Play tone based on amount of potentiometer movement'Activity board users use FREQOUT 11 instead of 1'****************** Declarations ************************'****************** VariablesPot_Current VAR WORD 'Current value of potentiometer Pot_Last VAR WORD 'Last value of potentiometer Freq_Play VAR WORD 'Tone to sound speaker

    Main:HIGH 7: PAUSE 1 ' Read Potentiometer using RCTIMERCTIME 7,1,Pot_Current ' and store as current pot valueFreq_Play = Pot_Current - Pot_Last ' Determine amount of change since last readingFREQOUT 1,500,Freq_Play ' Play tone based on changePot_Last = Pot_Current ' Save current pot value for last value

    GOTO Main

    106

    ConstantsConstantsConstants provide the ability to assign names to values thatConstants provide the ability to assign names to values that do not do not change.change. They allow an easier reading of code.They allow an easier reading of code.

    Unlike variables, which are used at run-time, constants are used whenUnlike variables, which are used at run-time, constants are used whenthe program is compiled or tokenized andthe program is compiled or tokenized and use no additional memory use no additional memory ..

    Common uses of constants:Common uses of constants:Naming of I/O pin numbers.Naming of I/O pin numbers.Naming of values which will not change such as PI (Note: the BS2Naming of values which will not change such as PI (Note: the BS2operates on whole numbers only).operates on whole numbers only).

    Constant names follow the same rules as variables and are declaredConstant names follow the same rules as variables and are declaredas follows:as follows:constantName CON valueconstantName CON value

    An example may be in Program 5C of naming the pin to which theAn example may be in Program 5C of naming the pin to which thespeaker is connected:speaker is connected:Speaker CON 1Speaker CON 1

  • 8/7/2019 Bs 2 Tutorial

    54/188

    107

    Coding with ConstantsCoding with ConstantsIn fact, let's clean up program 5C using constants.In fact, let's clean up program 5C using constants.

    By using constants the code is more readable, and if we need toBy using constants the code is more readable, and if we need tochange a pin connection, only the constant value needs to bechange a pin connection, only the constant value needs to beupdated.updated.

    'Prog 5D: Play tone based on amount of potentiometer movement using constants'****************** Declarations ************************'****************** VariablesPot_Current VAR WORD 'Current value of potentiometer Pot_Last VAR WORD 'Last value of potentiometer Freq_Play VAR WORD 'Tone to sound speaker '****************** ConstantsSpeaker CON 1 ' Speaker pin (Activity board users use 11)PotPin CON 7 ' Potentiometer pinSpeakerDur CON 500 ' Duration to sound speaker

    Main:HIGH PotPin : PAUSE 1 ' Read Potentiometer using RCTIMERCTIME PotPin ,1,Pot_Current ' and s tore as current pot valueFreq_Play = Pot_Current - Pot_Last ' Determine amount of chance since last readingFREQOUT Speaker , SpeakerDur , Freq_Play ' Play tone based on changePot_Last = Pot_Current ' Save current pot value for las t value

    GOTO Main

    108

    Challenge 5B: LED ConstantsChallenge 5B: LED ConstantsBelow is the challenge solution to blink 2 LEDs. Modify theBelow is the challenge solution to blink 2 LEDs. Modify thecode to use constant names for LED pin connections.code to use constant names for LED pin connections.

    '** 4B Challenge Solution Blink second LED **

    Main:LOW 8 'LED1 onHIGH 9 'LED2 off PAUSE 2000 'Wait 2 secondsLOW 9 'LED2 ON (P9 LED stays on)PAUSE 1000 'Wait 1 secondHIGH 8 'LED1 off HIGH 9 'LED2 off PAUSE 500 'Wait one-half second

    GOTO Main

    SolutionSolution

  • 8/7/2019 Bs 2 Tutorial

    55/188

    109

    I/O AliasesI/O AliasesJust as names can be assigned to RAM memory locationsJust as names can be assigned to RAM memory locationsusing the VAR instruction, VAR can be used to assignusing the VAR instruction, VAR can be used to assignnames to the status of I/O when using thenames to the status of I/O when using the ININ andand OUTOUT

    instructions. This creates aninstructions. This creates an aliasalias name for the I/O.name for the I/O.AliasName VAR INpinAliasName VAR INpinAliasName VAR OUTpinAliasName VAR OUTpin

    Example:Example: PB1 VAR IN10PB1 VAR IN10

    This allows for cleaner code and does not use anyThis allows for cleaner code and does not use anyadditional memory.additional memory.

    110

    Coding using I/O AliasesCoding using I/O AliasesLet's modify a previous program to make it a bit moreLet's modify a previous program to make it a bit morereadable using I/O aliases.readable using I/O aliases.

    Notice that OUTPUT and INPUT could not be made moreNotice that OUTPUT and INPUT could not be made morereadable without first assigning constants to the pinreadable without first assigning constants to the pinnumbers.numbers.

    '{$STAMP BS2}'Prog 5E: Controlling output LED1 with PB1 using I/O Variables

    ' **************** Declarations **************' **************** I/O AliasesPB1 VAR IN10 ' Pushbutton input pinLED1 VAR OUT8 ' LED1 output pin

    '**************** Set I/O DirectionsINPUT 10 'Set P10 to be an inputOUTPUT 8 'Set P8 to be an output

    Main: LED1 = PB1 'Set LED state = pushbutton stateGOTO Main 'Jump back to beginning

  • 8/7/2019 Bs 2 Tutorial

    56/188

    111

    Challenge 5C: I/O AliasesChallenge 5C: I/O AliasesCode a program that will control:Code a program that will control:LED2 on P9 with the PB1 on P10LED2 on P9 with the PB1 on P10LED1 on P8 with the PB2 on P11LED1 on P8 with the PB2 on P11

    SolutionSolution

    112

    Common Circuit DeclarationsCommon Circuit DeclarationsFor the remainder of this section, a commonFor the remainder of this section, a commonsection of declarations will apply to all thesection of declarations will apply to all theprograms to minimize the amount of coding andprograms to minimize the amount of coding andspace required.space required.

    In some cases an LED may be controlled withIn some cases an LED may be controlled withHIGH and LOW, other times it may be controlledHIGH and LOW, other times it may be controlledwith IN and OUT. Note that these 2 uses require 2with IN and OUT. Note that these 2 uses require 2different variables. If onlydifferent variables. If only LED1 VAR OUT8LED1 VAR OUT8 werewereused, a line of code such asused, a line of code such as HIGH LED1HIGH LED1 wouldwouldreally meanreally mean HIGH 1HIGH 1 or or HIGH 0HIGH 0 since LED1 wouldsince LED1 would

    return thereturn the valuevalue of OUT8.of OUT8.

  • 8/7/2019 Bs 2 Tutorial

    57/188

    113

    ' *********Section 5 Common Circuit Declarations ***********' ***************** I/O Aliases *******************LED1 VAR OUT8 'LED 1 pin I/OLED2 VAR OUT9 'LED 2 pin I/OPB1 VAR IN10 'Pushbu tton 1 p in I/O

    PB2 VAR IN11 'Pushbu tton 2 p in I/OPot VAR WORD Potentiometer value' **************** Constants ************************LED1_Pin CON 8 ' Cons tant to hold p in number o f LED 1LED2_Pin CON 9 ' Constant to hold pin number of LED 2PB1_Pin CON 10 ' Constant to hold pin number of pushbutton 1PB2_Pin CON 11 ' Constant to hold pin number of pushbutton 2Speaker CON 1 ' Speaker Pin ***** Activity board users set to 11 ******Pot_Pin CON 7 ' Input for Potentiometer RCTIME networkPB_On CON 0 ' Constant for state of pressed switch (Active-Low)PB_Off CON 1 ' Constant for state of un-pressed switchLED_On CON 0 ' Constant for state to light an LED (Active-Low)LED_Off CON 1 ' Constant for state to turn off an LED' **************** Set common I/O directions ********OUTPUT LED1_Pin 'Set pin for LED1 to be an outputOUTPUT LED2_Pin 'Set pin for LED2 to be an outputINPUT PB1_Pin 'Se t p in for pushbu tton 1 t o be an i nputINPUT PB2_Pin 'Se t p in for pushbu tton 2 t o be an i nput' **************** Example uses ***********************'LED2 = LED_On 'OUT9 = 0'LED1 = PB1 'OUT8 = IN10'HIGH LED1_Pin 'HIGH 8

    114

    SummarySummaryVariables are used to hold values that change inVariables are used to hold values that change inthe program.the program.

    There are 26 bytes available for variables.There are 26 bytes available for variables.

    Variables may be sized as bits, nibbles, bytes or Variables may be sized as bits, nibbles, bytes or words depending on the required size.words depending on the required size.

    Constants can be declared to hold name valuesConstants can be declared to hold name valuesthat DO NOT change.that DO NOT change.

    I/O pins can be names to give a descriptiveI/O pins can be names to give a descriptiveidentifier to the pin's use.identifier to the pin's use.

  • 8/7/2019 Bs 2 Tutorial

    58/188

    115

    End of Section 5End of Section 5

    116

    Section 6: Program FlowSection 6: Program Flow Introduction to FlowIntroduction to Flow

    Program Planning Pseudo-Code & FlowchartsProgram Planning Pseudo-Code & FlowchartsSequential FlowSequential Flow

    Sequential Flow ExampleSequential Flow ExampleBranching OverviewBranching Overview

    Looping with GOTOLooping with GOTOLooping Flow ExampleLooping Flow Example

    Conditionals OverviewConditionals OverviewIF-THENIF-THENIF-THEN Example: AlarmIF-THEN Example: AlarmLooping with a Counter Looping with a Counter Repeating AlarmRepeating AlarmFOR-NEXTFOR-NEXTRepeating Alarm with FOR-LoopRepeating Alarm with FOR-LoopSpeaker Tone with FOR-LoopSpeaker Tone with FOR-Loop

    SubroutinesSubroutinesCleaner Coding with GOSUBSCleaner Coding with GOSUBSSounding Alarms with GOSUBSounding Alarms with GOSUB

    Using the BRANCH InstructionUsing the BRANCH InstructionSaving Power END & SleepSaving Power END & Sleep

  • 8/7/2019 Bs 2 Tutorial

    59/188

    117

    Introduction to FlowIntroduction to FlowThe programs in the tutorial have been relatively easy andThe programs in the tutorial have been relatively easy andfollow a sequence of steps from top to bottom. At the endfollow a sequence of steps from top to bottom. At the endof each program, GOTO Main has been used to loop theof each program, GOTO Main has been used to loop theprogram back to the start.program back to the start.

    Virtually all microcontroller programs will continually repeatVirtually all microcontroller programs will continually repeatsince they are typically embedded in processes to besince they are typically embedded in processes to beoperated continually.operated continually.

    Sequential flow (top to bottom), looping, unconditionalSequential flow (top to bottom), looping, unconditionalbranching, and conditional branching will be explored inbranching, and conditional branching will be explored inthis section.this section.

    The newer PBASIC 2.5 implementation greatly extendsThe newer PBASIC 2.5 implementation greatly extendscontrol structures. Please reviewcontrol structures. Please review Appendix AAppendix A after thisafter thissection.section.

    118

    Program Planning Pseudo-Code & FlowchartsProgram Planning Pseudo-Code & Flowcharts

    Depending on your proficiency, a littleDepending on your proficiency, a little

    planning can help a lot in developingplanning can help a lot in developingprograms.programs.Plan your device placement carefully for goodPlan your device placement carefully for goodlayout and utilization of I/O.layout