BASIC Stamp Syntax and Reference Manual
Version 2.2
Warranty
Parallax Inc. warrants its products against defects in materials and workmanship for a period of 90 days from receipt of
product. If you discover a defect, Parallax Inc. will, at its option, repair or replace the merchandise, or refund the purchase
price. Before returning the product to Parallax, call for a Return Merchandise Authorization (RMA) number. Write the
RMA number on the outside of the box used to return the merchandise to Parallax. Please enclose the following along with
the returned merchandise: your name, telephone number, shipping address, and a description of the problem. Parallax will
return your product or its replacement using the same shipping method used to ship the product to Parallax.
14-Day Money-Back Guarantee
If, within 14 days of having received your product, you find that it does not suit your needs, you may return it for a full
refund. Parallax Inc. will refund the purchase price of the product, excluding shipping/handling costs. This guarantee is
void if the product has been altered or damaged. See the Warranty section above for instructions on returning a product to
Parallax.
Copyrights and Trademarks
This documentation is copyright 1994-2005 by Parallax Inc. By downloading or obtaining a printed copy of this
documentation or software you agree that it is to be used exclusively with Parallax products. Any other uses are not
permitted and may represent a violation of Parallax copyrights, legally punishable according to Federal copyright or
intellectual property laws. Any duplication of this documentation for commercial uses is expressly prohibited by Parallax
Inc. Duplication for educational use is permitted, subject to the following Conditions of Duplication: Parallax Inc. grants the
user a conditional right to download, duplicate, and distribute this text without Parallax’s permission. This right is based on
the following conditions: the text, or any portion thereof, may not be duplicated for commercial use; it may be duplicated
only for educational purposes when used solely in conjunction with Parallax products, and the user may recover from the
student only the cost of duplication.
This text is available in printed format from Parallax Inc. Because we print the text in volume, the consumer price is often
less than typical retail duplication charges.
BASIC Stamp, Stamps in Class, Board of Education, Boe-Bot, Todder, SumoBot, and SX-Key are registered trademarks of
Parallax, Inc. If you decide to use registered trademarks of Parallax Inc. on your web page or in printed material, you must
state that “(registered trademark) is a registered trademark of Parallax Inc.” upon the first appearance of the trademark
name in each printed document or web page. HomeWork Board, Parallax, and the Parallax logo are trademarks of Parallax
Inc. If you decide to use trademarks of Parallax Inc. on your web page or in printed material, you must state that
“(trademark) is a trademark of Parallax Inc.”, “upon the first appearance of the trademark name in each printed document
or web page. Other brand and product names are trademarks or registered trademarks of their respective holders.
ISBN #1-928982-32-8
Errata
While great effort is made to assure the accuracy of our texts, errors may still exist. If you find an error, please let us know
by sending an email to editor@parallax.com. We continually strive to improve all of our educational materials and
documentation, and frequently revise our texts. Occasionally, an errata sheet with a list of known errors and corrections for
a given text will be posted to our web site, www.parallax.com. Please check the individual product page’s free downloads
for an errata file.
Disclaimer of Liability
Parallax Inc. is not responsible for special, incidental, or consequential damages resulting from any breach of warranty, or
under any legal theory, including lost profits, downtime, goodwill, damage to or replacement of equipment or property, or
any costs of recovering, reprogramming, or reproducing any data stored in or used with Parallax products. Parallax Inc. is
also not responsible for any personal damage, including that to life and health, resulting from use of any of our products.
You take full responsibility for your BASIC Stamp application, no matter how life-threatening it may be.
Access Parallax via Internet
We maintain very a active web site for your convenience. These may be used to obtain software, communicate with
members of Parallax, and communicate with other customers. Access information is shown below:
Web:
General e-mail:
Tech. e-mail:
http://www.parallax.com
info@parallax.com
support@parallax.com
Internet BASIC Stamp Discussion List
We maintain active web-based discussion forums for people interested in Parallax products. These lists are accessible from
www.parallax.com via the Support → Discussion Forums menu. These are the forums that we operate from our web site:
•
•
•
•
•
•
•
BASIC Stamps – This list is widely utilized by engineers, hobbyists and students who share their BASIC
Stamp projects and ask questions.
®
Stamps in Class – Created for educators and students, subscribers discuss the use of the Stamps in
Class curriculum in their courses. The list provides an opportunity for both students and educators to
ask questions and get answers.
Parallax Educators –Exclusively for educators and those who contribute to the development of Stamps
in Class. Parallax created this group to obtain feedback on our curricula and to provide a forum for
educators to develop and obtain Teacher’s Guides.
Translators – The purpose of this list is to provide a conduit between Parallax and those who translate
our documentation to languages other than English. Parallax provides editable Word documents to our
translating partners and attempts to time the translations to coordinate with our publications.
Robotics – Designed exclusively for Parallax robots, this forum is intended to be an open dialogue for a
robotics enthusiasts. Topics include assembly, source code, expansion, and manual updates. The BoeBot®, Toddler®, SumoBot®, HexCrawler and QuadCrawler robots are discussed here.
SX Microcontrollers and SX-Key – Discussion of programming the SX microcontroller with Parallax
®
rd
assembly language SX – Key tools and 3 party BASIC and C compilers.
Javelin Stamp – Discussion of application and design using the Javelin Stamp, a Parallax module that is
®
programmed using a subset of Sun Microsystems’ Java programming language.
Supported Hardware, Firmware and Software
This manual is valid with the following software and firmware versions:
BASIC Stamp Model
BASIC Stamp 1
BASIC Stamp 2
BASIC Stamp 2e
BASIC Stamp 2sx
BASIC Stamp 2p
BASIC Stamp 2pe
BASIC Stamp 2px
Firmware
1.4
1.0
1.1
1.1
1.4
1.1
1.0
Windows Interface
2.2
2.2
2.2
2.2
2.2
2.2
2.2
The information herein will usually apply to newer versions but may not apply to older versions. New software can be
obtained free on web site (www.parallax.com). If you have any questions about what you need to upgrade your product,
please contact Parallax.
Credits
Authorship and Editorial Review Team: Jeff Martin, Jon Williams, Ken Gracey, Aristides Alvarez, and Stephanie Lindsay;
Cover Art: Jen Jacobs; Technical Graphics, Rich Allred; with many thanks to everyone at Parallax Inc.
Contents
PREFACE ...................................................................... 5
INTRODUCTION TO THE BASIC STAMP ..................................... 7
BASIC STAMP MODEL COMPARISON TABLE .........................................................................8
BASIC STAMP 1 HARDWARE .............................................................................................10
BASIC STAMP 2 HARDWARE .............................................................................................13
BASIC STAMP 2E HARDWARE ...........................................................................................15
BASIC STAMP 2SX HARDWARE .........................................................................................17
BASIC STAMP 2P HARDWARE ...........................................................................................19
BASIC STAMP 2PE HARDWARE .........................................................................................21
BASIC STAMP 2PX HARDWARE .........................................................................................23
GUIDELINES AND PRECAUTIONS .........................................................................................25
BASIC STAMP PROGRAMMING CONNECTIONS ....................................................................27
QUICK START GUIDE ....................................................... 29
USING THE BASIC STAMP EDITOR........................................ 35
THE PROGRAMMING ENVIRONMENT ....................................................................................35
COMPILER DIRECTIVES ......................................................................................................43
SPECIAL FUNCTIONS .........................................................................................................46
SETTING PREFERENCES ....................................................................................................55
ADVANCED COMPILATION TECHNIQUES ..............................................................................68
FEATURES FOR DEVELOPERS.............................................................................................75
BASIC STAMP ARCHITECTURE............................................ 81
RAM ORGANIZATION (BS1)...............................................................................................81
RAM ORGANIZATION (BS2, BS2E, BS2SX, BS2P, BS2PE) .................................................82
DEFINING AND USING VARIABLES .......................................................................................84
The Rules of Symbol Names ......................................................................................86
Defining Array Variables .............................................................................................87
Aliases and Variable Modifiers ...................................................................................89
CONSTANTS AND COMPILE-TIME EXPRESSIONS ...................................................................94
NUMBER REPRESENTATIONS..............................................................................................96
ORDER OF OPERATIONS ..................................................................................................102
INTEGER MATH RULES .....................................................................................................103
UNARY OPERATORS ........................................................................................................105
Absolute Value (ABS) ...............................................................................................105
Cosine (COS) ...........................................................................................................106
Decoder (DCD) .........................................................................................................106
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 1
Contents
Negative (-)...............................................................................................................106
Encoder (NCD) .........................................................................................................107
Sine (SIN) .................................................................................................................107
Square Root (SQR) ..................................................................................................108
BINARY OPERATORS .......................................................................................................109
Add (+)......................................................................................................................109
Subtract (-)................................................................................................................110
Multiply (*).................................................................................................................110
Multiply High (**).......................................................................................................111
Multiply Middle (*/) ....................................................................................................112
Divide (/) ...................................................................................................................113
Modulus (//)...............................................................................................................113
Arctangent (ATN)......................................................................................................114
Hypotenuse (HYP)....................................................................................................115
Minimum (MIN) .........................................................................................................115
Maximum (MAX).......................................................................................................116
Digit (DIG).................................................................................................................117
Shift Left () .........................................................................................................117
Reverse (REV) .........................................................................................................118
And (&) .....................................................................................................................118
Or (|) .........................................................................................................................118
Xor (^).......................................................................................................................119
And Not (&/)..............................................................................................................120
Or Not (|/)..................................................................................................................120
Xor Not (^/) ...............................................................................................................121
BASIC STAMP COMMAND REFERENCE ................................. 123
PBASIC LANGUAGE VERSIONS .......................................................................................123
CATEGORICAL LISTING OF COMMANDS .............................................................................124
SYNTAX CONVENTIONS....................................................................................................128
AUXIO...........................................................................................................................129
BRANCH.......................................................................................................................133
BUTTON .......................................................................................................................137
COMPARE....................................................................................................................141
CONFIGPIN ..................................................................................................................143
COUNT .........................................................................................................................149
DATA ............................................................................................................................153
DEBUG .........................................................................................................................159
DEBUGIN......................................................................................................................171
DO...LOOP....................................................................................................................175
Page 2 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Contents
DTMFOUT.....................................................................................................................179
EEPROM.......................................................................................................................183
END...............................................................................................................................187
EXIT ..............................................................................................................................189
FOR…NEXT .................................................................................................................191
FREQOUT.....................................................................................................................199
GET...............................................................................................................................203
GOSUB .........................................................................................................................209
GOTO............................................................................................................................213
HIGH .............................................................................................................................215
I2CIN.............................................................................................................................217
I2COUT.........................................................................................................................225
IF…THEN......................................................................................................................231
INPUT ...........................................................................................................................243
IOTERM ........................................................................................................................247
LCDCMD.......................................................................................................................249
LCDIN ...........................................................................................................................257
LCDOUT .......................................................................................................................263
LET................................................................................................................................269
LOOKDOWN.................................................................................................................271
LOOKUP .......................................................................................................................277
LOW..............................................................................................................................281
MAINIO .........................................................................................................................283
NAP...............................................................................................................................285
ON.................................................................................................................................289
OUTPUT .......................................................................................................................293
OWIN ............................................................................................................................295
OWOUT ........................................................................................................................303
PAUSE..........................................................................................................................311
POLLIN .........................................................................................................................313
POLLMODE ..................................................................................................................319
POLLOUT .....................................................................................................................325
POLLRUN .....................................................................................................................331
POLLWAIT....................................................................................................................335
POT...............................................................................................................................339
PULSIN .........................................................................................................................343
PULSOUT .....................................................................................................................347
PUT...............................................................................................................................351
PWM .............................................................................................................................355
RANDOM ......................................................................................................................359
RCTIME ........................................................................................................................363
READ ............................................................................................................................369
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 3
Contents
RETURN .......................................................................................................................375
REVERSE.....................................................................................................................377
RUN ..............................................................................................................................381
SELECT...CASE ...........................................................................................................387
SERIN ...........................................................................................................................393
SEROUT .......................................................................................................................415
SHIFTIN ........................................................................................................................431
SHIFTOUT ....................................................................................................................435
SLEEP ..........................................................................................................................441
SOUND .........................................................................................................................445
STOP ............................................................................................................................447
STORE..........................................................................................................................449
TOGGLE.......................................................................................................................455
WRITE ..........................................................................................................................459
XOUT............................................................................................................................465
APPENDIX A: ASCII CHART .............................................. 471
APPENDIX B: RESERVED WORDS ........................................ 473
APPENDIX C: CONVERSION FORMATTERS ............................. 477
APPENDIX D: BASIC STAMP SCHEMATICS ............................. 481
Page 4 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Preface
Thank you for purchasing a Parallax BASIC Stamp® microcontroller
module. We have done our best to produce several full-featured, easy to
use development systems for BASIC Stamp microcontrollers. Depending
on the Starter Kit you purchased, your BASIC Stamp model, development
board and other contents will vary.
This manual is written for the latest available BASIC Stamp modules and
software as of February 2005.
As the product-line evolves, new
information may become available. It is always recommended to visit the
Parallax web site, www.parallax.com, for the latest information.
This manual is intended to be a complete reference manual to the
architecture and command structure of the various BASIC Stamp models.
This manual is not meant to teach BASIC programming or electrical
design; though a person can learn a lot by paying close attention to the
details in this book.
If you have never programmed in the BASIC language or are unfamiliar
with electronics, it would be best to locate one or more of the books listed
on the following page for assistance. All are available, either to order or
to download, from www.parallax.com.
Books available in Adobe’s PDF format are published for free download
on the Parallax web site or on the CD-ROM which ships with our different
Starter Kits. Books available in print may be purchased directly from
Parallax or other distributors.
In addition, there are hundreds of great examples available on the Parallax
CD and web site (www.parallax.com). Also, Nuts & Volts Magazine
(www.nutsvolts.com / 1-800-783-4624) is a national electronic hobbyist's
magazine that features monthly articles featuring BASIC Stamp
applications. This is an excellent resource for beginners and experts alike!
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 5
Preface
Book
What’s a Microcontroller?
Robotics with the
Boe-Bot
IR Remote for the
Boe-Bot
Basic Analog and Digital
Applied Sensors
Understanding Signals
Industrial Control
Elements of Digital Logic
The Microcontroller Application
Cookbook Volumes 1 and 2
Al’s “World Famous” Stamp Project
of the Month Anthology
The Nuts and Volts of BASIC Stamps
Volumes 1, 2, 3, 4, and 5
StampWorks
Stamp 2 Communication and Control
Projects
Programming and Customizing the
BASIC Stamp Computer
BASIC Stamp 2p
Part #
28123
Author and Publisher
Andy Lindsay; Parallax Inc.;
ISBN 1-928982-02-6
28125
Andy Lindsay; Parallax Inc.;
ISBN 1-928982-03-4
70016
Andy Lindsay; Parallax Inc.;
ISBN 1-928982-31-X
28129
Andy Lindsay; Parallax Inc.;
ISBN 1-928982-04-2
28127
Tracy Allen, PhD.; Parallax Inc.; ISBN 1928982-21-2
28119
Doug Pientak; Parallax Inc.;
(With Full Kit)
ISBN 1-928982-23-9
27341
Marty Hebel / Will Devenport;
Parallax Inc.; ISBN 1-928982-08-5
70008
John Barrowman; Parallax Inc.; ISBN 1928982-20-4
Vol. 1&2: 28113
Matt Gilliland; Woodglen Press;
Vol. 2: 28112
ISBN 0-616-11552-7 and 0-972-01590-6
70013
Al Williams; Parallax Inc.;
ISBN 1-928982-25-5
Vol. 4: 70010
Jon Williams, Scott Edwards and Lon
Vol. 5: 70015
Glazner; Parallax, Inc.;
ISBN 1-928982-10-7, 1-928982-11-5,
1-928982-17-4, 1-928982-24-7
and 1-928982-30-1
27220
Jon Williams; Parallax, Inc.;
ISBN 1-928982-07-7
70004
Thomas Petruzzellis; McGraw-Hill;
ISBN 0-071411-97-6
27956
Scott Edwards; McGraw-Hill;
ISBN 0-071371-92-3
70001
Claus Kuehnel and Klaus Zahnert;
Parallax, Inc.; ISBN 1-928982-19-0
Page 6 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Availability
PDF
In Print
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
Yes
Portions
Yes
Yes
(all)
Yes
(Vol 4 and
Vol 5)
Yes
Yes
No
Yes
No
Yes
Yes
No
1: Introduction to the BASIC Stamp
Welcome to the wonderful world of BASIC Stamp® microntrollers. BASIC
Stamp microcontrollers have been in use by engineers and hobbyists since
we first introduced them in 1992. As of November 2004, Parallax
customers have put well over three million BASIC Stamp modules into
use. Over this 12-year period, the BASIC Stamp line of controllers has
evolved into six models and many physical package types, explained
below.
General Operation Theory
BASIC Stamp modules are microcontrollers (tiny computers) that are
designed for use in a wide array of applications. Many projects that
require an embedded system with some level of intelligence can use a
BASIC Stamp module as the controller.
Each BASIC Stamp comes with a BASIC Interpreter chip, internal memory
(RAM and EEPROM), a 5-volt regulator, a number of general-purpose I/O
pins (TTL-level, 0-5 volts), and a set of built-in commands for math and
I/O pin operations. BASIC Stamp modules are capable of running a few
thousand instructions per second and are programmed with a simplified,
but customized form of the BASIC programming language, called
PBASIC.
PBASIC Language
We developed PBASIC specifically for the BASIC Stamp as a simple, easy
to learn language that is also well suited for this architecture, and highly
optimized for embedded control. It includes many of the instructions
featured in other forms of BASIC (GOTO, FOR...NEXT, IF...THEN…ELSE)
as well as some specialized instructions (SERIN, PWM, BUTTON, COUNT
and DTMFOUT). This manual includes an extensive section devoted to
each of the available instructions.
Hardware
At the time of this writing, there are currently seven models of the BASIC
Stamp; the BS1, BS2, BS2e, BS2sx, BS2p, BS2pe, and the BS2px. The tables
below are provided to easily compare their specifications, followed by
diagrams that detail the various package types of these modules.
Schematics for the SIP/DIP packages of all models can be found in
Appendix D.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 7
Introduction to the BASIC Stamp
BASIC Stamp Model Comparison Table
Products
BS1
BS2
BS2e
Environment
0º - 70º C
(32º - 158º F) **
0º - 70º C (32º - 158º F) **
0º - 70º C (32º - 158º F) **
Microcontroller
Microchip PIC16C56a
Microchip PIC16C57c
Ubicom SX28AC
Processor Speed
4 MHz
20 MHz
20 MHz
Program Execution Speed
~2,000 instructions/sec.
~4,000
instructions/sec
~4,000 instructions/sec
RAM Size
16 Bytes (2 I/O, 14 Variable)
32 Bytes
(6 I/O, 26 Variable)
32 Bytes (6 I/O, 26 Variable)
Scratch PadRam
N/A
N/A
64 Bytes
EEPROM (Program) Size
256 Bytes,
~80 instructions
2K Bytes,
~500 instructions
8 x 2K Bytes,
~4,000 inst
Number of I/O Pins
8
16 + 2 Dedicated Serial
16 + 2 Dedicated Serial
Voltage Requirements
5 - 15 vdc
5 - 15 vdc
5 - 12 vdc
Current Draw@ 5 volts
1 mA Run,
25 µA Sleep
3 mA Run,
50 µA Sleep
25 mA Run,
200 µA Sleep
Source/Sink Current per I/O
20 mA / 25 mA
20 mA / 25 mA
30 mA / 30 mA
Source/Sink
Current per unit
40 mA / 50 mA
40 mA / 50 mA
per 8 I/O pins
60 mA / 60 mA
per 8 I/O pins
PBASIC Commands*
32
42
45
PC Interface
Serial
(w/BS1 Serial Adapter)
Serial
(9600 baud)
Serial (9600 baud)
Windows Text Editor
Stampw.exe (v2.1 and up)
Stampw.exe (v1.04 and up)
Version
* PBASIC Command count totals include PBASIC 2.5 commands on all BS2 models.
** See below for industrial rated module information.
Industrial-Rated BASIC Stamp Modules
Some BASIC Stamp models come in Industrial-rated versions, with an
environmental temperature tolerance range of -40°C to +85°C . Contact
the Parallax Sales Team directly for the latest information regarding
industrial-rated product availability and specifications.
Page 8 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Stampw.exe
(v1.096 and up)
1: Introduction to the BASIC Stamp
BS2sx
BS2p24
BS2p40
BS2pe
BS2px
0º - 70º C
(32º - 158º F) **
0º - 70º C
(32º - 158º F) **
0º - 70º C
(32º - 158º F) **
0º - 70º C
(32º - 158º F) **
0º - 70º C
(32º - 158º F) **
Ubicom SX28AC
Ubicom SX48AC
Ubicom SX48AC
Ubicom SX48AC
Ubicom SX48AC
50 MHz
20 MHz Turbo
20 MHz Turbo
8 MHz Turbo
32 MHz Turbo
~6000 instructions/sec.
~19,000 instructions/sec.
~10,000 instructions/sec. ~12,000 instructions/sec. ~12,000 instructions/sec.
32 Bytes
(6 I/O, 26 Variable)
38 Bytes
(12 I/O, 26 Variable)
38 Bytes
(12 I/O, 26 Variable)
38 Bytes
(12 I/O, 26 Variable)
38 Bytes
(12 I/O, 26 Variable)
64 Bytes
128 Bytes
128 Bytes
128 Bytes
128 Bytes
8 x 2K Bytes,
~4,000 inst.
8 x 2K Bytes,
~4,000 inst.
8 x 2K Bytes,
~4,000 inst.
16 x 2K Bytes
(16 K for source)
8 x 2K Bytes,
~4,000 inst.
16 + 2 Dedicated Serial
16 + 2 Dedicated Serial
32 + 2 Dedicated Serial
16 + 2 Dedicated Serial
16 + 2 Dedicated Serial
5 - 12 vdc
5 - 12 vdc
5 - 12 vdc
5 - 12 vdc
5 - 12 vdc
60 mA Run,
500 µA Sleep
40 mA Run,
350 µA Sleep
40 mA Run,
350 µA Sleep
15 mA Run,
150 µA Sleep
55 mA Run,
450 µA Sleep
30 mA / 30 mA
30 mA /
30 mA
30 mA / 30 mA
30 mA / 30 mA
30 mA / 30 mA
60 mA / 60 mA
per 8 I/O pins
60 mA / 60 mA
per 8 I/O pins
60 mA /60 mA
per 8 I/O pins
60 mA / 60 mA
per 8 I/O pins
60 mA / 60 mA
per 8 I/O pins
45
61
61
61
63
Serial (9600 baud)
Serial (9600 baud)
Serial
(9600 baud)
Serial (9600 baud)
Serial (19200 baud)
Stampw.exe
(v1.091 and up)
Stampw.exe
(v1.1 and up)
Stampw.exe
(v1.1 and up)
Stampw.exe
(v1.33 and up)
Stampw.exe
(v2.2 and up)
Phone: (916) 624-8333
Toll free in the US or Canada: 1-888-512-1024
Email: sales@parallax.com
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 9
Introduction to the BASIC Stamp
BASIC Stamp 1
Figure 1.1: BASIC Stamp 1
(Rev B) (Stock# BS1-IC).
Figure 1.2: BASIC Stamp 1 OEM
(Rev. A) (Stock# 27295).
Page 10 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
1: Introduction to the BASIC Stamp
Figure 1.3: BASIC Stamp 1
(Rev Dx) (Stock# 27100).
The BASIC Stamp 1 is available several physical packages. The BS1-IC
(Figure 1.1) uses surface mount components to fit in a small 14-pin SIP
package. The preassembled BASIC Stamp 1 OEM (Figure 1.2) features an
easier-to-trace layout meant to aid customers who wish to integrate the
BASIC Stamp 1 circuit directly into their design (as a lower-cost solution).
The BASIC Stamp 1 Rev. Dx (simply called the Rev. Dx), see Figure 1.3,
includes a prototyping area suitable for soldering electronic components.
These three packages are functionally equivalent, except that the Rev. Dx
does not have an available reset pin.
In addition to the packages shown, there are prototyping boards available
that feature a surface mounted BS1 and programming cable connector.
Please check www.parallax.com → Products → Development Boards for
product descriptions.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 11
Introduction to the BASIC Stamp
Pin
Name
1
VIN
2
VSS
3
4
PCO
PCI
5
VDD
6
RES
7-14
P0-P7
Description
Unregulated power in: accepts 5.5 - 15 VDC (6-40 VDC on
BS1-IC rev. b), which is then internally regulated to 5 volts. May
be left unconnected if 5 volts is applied to the VDD (+5V) pin.
System ground: connects to BS1 Serial Adapter ground for
programming.
PC Out: 4800 baud serial output (TTL level) to PC.
PC In: 4800 baud serial input (TTL level) from PC.
5-volt DC input/output: (Also called +5V) if an unregulated voltage
is applied to the VIN pin, then this pin will output 5 volts. If no
voltage is applied to the VIN pin, then a regulated voltage
between 4.5V and 5.5V should be applied to this pin.
Reset input/output: goes low when power supply is less than
approximately 4.2 volts, causing the BASIC Stamp to reset. Can
be driven low to force a reset. This pin is internally pulled high
and may be left disconnected if not needed. Do not drive high.
General-purpose I/O pins: each can sink 25 mA and source 20
mA. However, the total of all pins should not exceed 50 mA (sink)
and 40 mA (source).
See the "BASIC Stamp Programming Connections" section on page 27 for
more information on the required programming connections between the
PC and the BASIC Stamp.
Page 12 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 1.1: BASIC Stamp 1 Pin
Descriptions.
1: Introduction to the BASIC Stamp
BASIC Stamp 2
Figure 1.4: BASIC Stamp 2
(Rev. G) (Stock# BS2-IC).
Figure 1.5: BASIC Stamp 2 OEM
(Rev. A2) (Stock# 27290 assembled,
or #27291 in kit form).
The BASIC Stamp 2 is available in several physical packages. The BS2-IC
(Figure 1.4) uses surface mount components to fit in a small 24-pin DIP
package. The BASIC Stamp 2 OEM (Figure 1.5) features an easier-to-trace
layout meant to aid customers who wish to integrate the BASIC Stamp 2
circuit directly into their design (as a lower-cost solution). The BASIC
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 13
Introduction to the BASIC Stamp
Stamp 2 OEM is available in either an assembled form or a kit form. These
three packages are functionally equivalent.
In addition to the dual-inline and OEM packages, there are prototyping
boards available that feature a surface mounted BS2. Please check
www.parallax.com → Products → Development Boards for product
descriptions.
Pin
Name
1
SOUT
2
SIN
3
ATN
4
VSS
5-20
P0-P15
21
VDD
22
RES
23
VSS
24
VIN
Description
Serial Out: connects to PC serial port RX pin (DB9 pin 2 / DB25
pin 3) for programming.
Serial In: connects to PC serial port TX pin (DB9 pin 3 / DB25 pin
2) for programming.
Attention: connects to PC serial port DTR pin (DB9 pin 4 / DB25
pin 20) for programming.
System ground: (same as pin 23) connects to PC serial port GND
pin (DB9 pin 5 / DB25 pin 7) for programming.
General-purpose I/O pins: each can sink 25 mA and source 20
mA. However, the total of all pins should not exceed 50 mA (sink)
and 40 mA (source) if using the internal 5-volt regulator. The total
per 8-pin groups (P0 – P7 or P8 – 15) should not exceed 50 mA
(sink) and 40 mA (source) if using an external 5-volt regulator.
5-volt DC input/output: if an unregulated voltage is applied to the
VIN pin, then this pin will output 5 volts. If no voltage is applied to
the VIN pin, then a regulated voltage between 4.5V and 5.5V
should be applied to this pin.
Reset input/output: goes low when power supply is less than
approximately 4.2 volts, causing the BASIC Stamp to reset. Can
be driven low to force a reset. This pin is internally pulled high
and may be left disconnected if not needed. Do not drive high.
System ground: (same as pin 4) connects to power supply’s
ground (GND) terminal.
Unregulated power in: accepts 5.5 - 15 VDC (6-40 VDC on BS2IC Rev. e, f, and g), which is then internally regulated to 5 volts.
Must be left unconnected if 5 volts is applied to the VDD (+5V)
pin.
See the "BASIC Stamp Programming Connections" section on page 27 for
more information on the required programming connections between the
PC and the BASIC Stamp.
Page 14 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 1.2: BASIC Stamp 2 Pin
Descriptions.
1: Introduction to the BASIC Stamp
BASIC Stamp 2e
Figure 1.6: BASIC Stamp 2e
(Rev. B) (Stock# BS2E-IC).
The BASIC Stamp 2e is available in the above 24-pin DIP package.
Table 1.3: BASIC Stamp 2e Pin
Descriptions.
Pin
Name
1
SOUT
2
SIN
3
ATN
4
VSS
5-20
P0-P15
21
VDD
22
RES
23
VSS
24
VIN
Description
Serial Out: connects to PC serial port RX pin (DB9 pin 2 / DB25
pin 3) for programming.
Serial In: connects to PC serial port TX pin (DB9 pin 3 / DB25 pin
2) for programming.
Attention: connects to PC serial port DTR pin (DB9 pin 4 / DB25
pin 20) for programming.
System ground: (same as pin 23) connects to PC serial port GND
pin (DB9 pin 5 / DB25 pin 7) for programming.
General-purpose I/O pins: each can source and sink 30 mA.
However, the total of all pins should not exceed 75 mA (source or
sink) if using the internal 5-volt regulator. The total per 8-pin
groups (P0 – P7 or P8 – 15) should not exceed 100 mA (source
or sink) if using an external 5-volt regulator.
5-volt DC input/output: if an unregulated voltage is applied to the
VIN pin, then this pin will output 5 volts. If no voltage is applied to
the VIN pin, then a regulated voltage between 4.5V and 5.5V
should be applied to this pin.
Reset input/output: goes low when power supply is less than
approximately 4.2 volts, causing the BASIC Stamp to reset. Can
be driven low to force a reset. This pin is internally pulled high
and may be left disconnected if not needed. Do not drive high.
System ground: (same as pin 4) connects to power supply’s
ground (GND) terminal.
Unregulated power in: accepts 5.5 - 12 VDC (7.5 recommended),
which is then internally regulated to 5 volts. Must be left
unconnected if 5 volts is applied to the VDD (+5V) pin.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 15
Introduction to the BASIC Stamp
See the "BASIC Stamp Programming Connections" section on page 27 for
more information on the required programming connections between the
PC and the BASIC Stamp.
Page 16 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
1: Introduction to the BASIC Stamp
BASIC Stamp 2sx
Figure 1.7: BASIC Stamp 2sx
(Rev. E) (Stock# BS2sx-IC)
Figure 1.8: BASIC Stamp 2sx OEM
(Rev. A2) (Stock# 27294)
The BASIC Stamp 2sx is available in the above two physical packages.
The BS2sx-IC (Figure 1.7) uses surface mount components to fit in a small
24-pin DIP package. The preassembled BASIC Stamp 2sx OEM (Figure
1.8) features an easier-to-trace layout meant to aid customers who wish to
integrate the BASIC Stamp 2sx circuit directly into their design (as a
lower-cost solution). The BASIC Stamp 2sx OEM is available in assembled
form only.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 17
Introduction to the BASIC Stamp
Pin
Name
1
SOUT
2
SIN
3
ATN
4
VSS
5-20
P0-P15
21
VDD
22
RES
23
VSS
24
VIN
Description
Serial Out: connects to PC serial port RX pin (DB9 pin 2 / DB25
pin 3) for programming.
Serial In: connects to PC serial port TX pin (DB9 pin 3 / DB25
pin 2) for programming.
Attention: connects to PC serial port DTR pin (DB9 pin 4 / DB25
pin 20) for programming.
System ground: (same as pin 23) connects to PC serial port
GND pin (DB9 pin 5 / DB25 pin 7) for programming.
General-purpose I/O pins: each can source and sink 30 mA.
However, the total of all pins should not exceed 75 mA (source
or sink) if using the internal 5-volt regulator. The total per 8-pin
groups (P0 – P7 or P8 – 15) should not exceed 100 mA (source
or sink) if using an external 5-volt regulator.
5-volt DC input/output: if an unregulated voltage is applied to
the VIN pin, then this pin will output 5 volts. If no voltage is
applied to the VIN pin, then a regulated voltage between 4.5V
and 5.5V should be applied to this pin.
Reset input/output: goes low when power supply is less than
approximately 4.2 volts, causing the BASIC Stamp to reset.
Can be driven low to force a reset. This pin is internally pulled
high and may be left disconnected if not needed. Do not drive
high.
System ground: (same as pin 4) connects to power supply’s
ground (GND) terminal.
Unregulated power in: accepts 5.5 - 12 VDC (7.5
recommended), which is then internally regulated to 5 volts.
Must be left unconnected if 5 volts is applied to the VDD (+5V)
pin.
See the "BASIC Stamp Programming Connections" section on page 27 for
more information on the required programming connections between the
PC and the BASIC Stamp.
Page 18 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 1.4: BASIC Stamp 2sx Pin
Descriptions
1: Introduction to the BASIC Stamp
BASIC Stamp 2p
Figure 1.9: BASIC Stamp 2p24
(Rev. C) (Stock# BS2p24-IC)
This module is identical in function
to the BS2p40-IC, except that it has
16 I/O pins.
Figure 1.10: BASIC Stamp 2p40
(Rev. B) (Stock# BS2p40-IC)
This module is identical in function
to the BS2p24-IC, except that it has
32 I/O pins.
The BASIC Stamp 2p is available in the above two physical packages.
Both packages use surface mount components to fit in a small package.
The BS2p24-IC (Figure 1.9) is a 24-pin DIP package. The BS2p40-IC
(Figure 1.10) is a 40-pin DIP package. Both packages are functionally
equivalent accept that the BS2p40 has 32 I/O pins instead of 16.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 19
Introduction to the BASIC Stamp
Pin
Name
1
SOUT
2
SIN
3
ATN
4
VSS
5-20
P0-P15
{21-36}
X0-X15
21 {37}
VDD
22 {38}
RES
23 {39}
VSS
24 {40}
VIN
Description
Serial Out: connects to PC serial port RX pin (DB9 pin 2 / DB25
pin 3) for programming.
Serial In: connects to PC serial port TX pin (DB9 pin 3 / DB25 pin
2) for programming.
Attention: connects to PC serial port DTR pin (DB9 pin 4 / DB25
pin 20) for programming.
System ground: (same as pin 23 on BS2p24, or pin 39 on
BS2p40) connects to PC serial port GND pin (DB9 pin 5 / DB25
pin 7) for programming.
General-purpose I/O pins: each can source and sink 30 mA.
However, the total of all pins (including X0-X15, if using the
BS2p40) should not exceed 75 mA (source or sink) if using the
internal 5-volt regulator. The total per 8-pin groups (P0 – P7, P8
– 15, X0 – X7 or X8 – X15) should not exceed 100 mA (source or
sink) if using an external 5-volt regulator.
(BS2p40 Only!) Auxiliary Bank of General-purpose I/O pins: each
can source and sink 30 mA. However, the total of all pins
(including P0 – P15) should not exceed 75 mA (source or sink) if
using the internal 5-volt regulator. The total per 8-pin groups (P0
– P7, P8 – 15, X0 – X7 or X8 – X15) should not exceed 100 mA
(source or sink) if using an external 5-volt regulator.
5-volt DC input/output: if an unregulated voltage is applied to the
VIN pin, then this pin will output 5 volts. If no voltage is applied to
the VIN pin, then a regulated voltage between 4.5V and 5.5V
should be applied to this pin.
Reset input/output: goes low when power supply is less than
approximately 4.2 volts, causing the BASIC Stamp to reset. Can
be driven low to force a reset. This pin is internally pulled high
and may be left disconnected if not needed. Do not drive high.
System ground: (same as pin 4) connects to power supply’s
ground (GND) terminal.
Unregulated power in: accepts 5.5 - 12 VDC (7.5 recommended),
which is then internally regulated to 5 volts. Must be left
unconnected if 5 volts is applied to the VDD (+5V) pin.
See the "BASIC Stamp Programming Connections" section on page 27 for
more information on the required programming connections between the
PC and the BASIC Stamp.
Page 20 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 1.5: BASIC Stamp 2p Pin
Connections
1: Introduction to the BASIC Stamp
Basic Stamp 2pe
Figure 1.11: BASIC Stamp 2pe
(Rev. B) (Stock# BS2pe-IC)
The BASIC Stamp 2pe is available in the above 24-pin DIP physical
package.
Table 1.6: BASIC Stamp 2pe Pin
Descriptions.
Pin
Name
1
SOUT
2
SIN
3
ATN
4
VSS
5-20
P0-P15
21
VDD
22
RES
23
VSS
24
VIN
Description
Serial Out: connects to PC serial port RX pin (DB9 pin 2 / DB25 pin 3)
for programming.
Serial In: connects to PC serial port TX pin (DB9 pin 3 / DB25 pin 2)
for programming.
Attention: connects to PC serial port DTR pin (DB9 pin 4 / DB25 pin
20) for programming.
System ground: (same as pin 23), connects to PC serial port GND pin
(DB9 pin 5 / DB25 pin 7) for programming.
General-purpose I/O pins: each can source and sink 30 mA.
However, the total of all pins should not exceed 75 mA (source or
sink) if using the internal 5-volt regulator. The total per 8-pin groups
P0 – P7 or P8 – 15 should not exceed 100 mA (source or sink) if
using an external 5-volt regulator.
5-volt DC input/output: if an unregulated voltage is applied to the VIN
pin, then this pin will output 5 volts. If no voltage is applied to the VIN
pin, then a regulated voltage between 4.5V and 5.5V should be
applied to this pin.
Reset input/output: goes low when power supply is less than
approximately 4.2 volts, causing the BASIC Stamp to reset. Can be
driven low to force a reset. This pin is internally pulled high and may
be left disconnected if not needed. Do not drive high.
System ground: (same as pin 4) connects to power supply’s ground
(GND) terminal.
Unregulated power in: accepts 5.5 - 12 VDC (7.5 recommended),
which is then internally regulated to 5 volts. Must be left unconnected
if 5 volts is applied to the VDD (+5V) pin.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 21
Introduction to the BASIC Stamp
See the "BASIC Stamp Programming Connections" section on page 27 for
more information on the required programming connections between the
PC and the BASIC Stamp.
Page 22 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
1: Introduction to the BASIC Stamp
Basic Stamp 2px
Figure 1.12: BASIC Stamp 2px
(Rev. A) (Stock# BS2px-IC)
The BASIC Stamp 2px is available in the above 24-pin DIP physical
package.
Table 1.7: BASIC Stamp 2px Pin
Descriptions.
Pin
Name
1
SOUT
2
SIN
3
ATN
4
VSS
5-20
P0-P15
21
VDD
22
RES
23
VSS
24
VIN
Description
Serial Out: connects to PC serial port RX pin (DB9 pin 2 / DB25 pin 3)
for programming.
Serial In: connects to PC serial port TX pin (DB9 pin 3 / DB25 pin 2)
for programming.
Attention: connects to PC serial port DTR pin (DB9 pin 4 / DB25 pin
20) for programming.
System ground: (same as pin 23), connects to PC serial port GND pin
(DB9 pin 5 / DB25 pin 7) for programming.
General-purpose I/O pins: each can source and sink 30 mA.
However, the total of all pins should not exceed 75 mA (source or
sink) if using the internal 5-volt regulator. The total per 8-pin groups
P0 – P7 or P8 – 15 should not exceed 100 mA (source or sink) if
using an external 5-volt regulator.
5-volt DC input/output: if an unregulated voltage is applied to the VIN
pin, then this pin will output 5 volts. If no voltage is applied to the VIN
pin, then a regulated voltage between 4.5V and 5.5V should be
applied to this pin.
Reset input/output: goes low when power supply is less than
approximately 4.2 volts, causing the BASIC Stamp to reset. Can be
driven low to force a reset. This pin is internally pulled high and may
be left disconnected if not needed. Do not drive high.
System ground: (same as pin 4) connects to power supply’s ground
(GND) terminal.
Unregulated power in: accepts 5.5 - 12 VDC (7.5 recommended),
which is then internally regulated to 5 volts. Must be left unconnected
if 5 volts is applied to the VDD (+5V) pin.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 23
Introduction to the BASIC Stamp
See the "BASIC Stamp Programming Connections" section on page 27 for
more information on the required programming connections between the
PC and the BASIC Stamp.
Page 24 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
1: Introduction to the BASIC Stamp
Guidelines and Precautions
When using the BASIC Stamp, or any IC chip, please follow the
guidelines below.
1.
2.
3.
Be alert to static sensitive devices and static-prone situations.
a. The BASIC Stamp, like other IC’s, can be damaged by
static discharge that commonly occurs touching
grounded surfaces or other conductors. Environmental
conditions (humidity changes, wind, static prone
surfaces, etc) play a major role in the presence of random
static charges.
It is always recommended to use
grounding straps and anti-static or static dissipative mats
when handling devices like the BASIC Stamp. If the
items above are not available, be sure to touch a
grounded surface after you have approached the work
area and before you handle static sensitive devices.
Verify that all power is off before connecting/disconnecting.
a. If power is connected to the BASIC Stamp or any device it
is connected to while inserting or removing it from a
circuit, damage to the BASIC Stamp or circuit could
result.
Verify BASIC Stamp orientation before connection to
development boards and other circuits.
a. Like other IC’s, the BASIC Stamp should be inserted in a
specific orientation in relation to the development board
or circuit. Powering the circuit with an IC connected
backwards will likely damage the IC and/or other
components in the circuit. Most IC’s have some form of a
“pin 1 indicator” as do most IC sockets. This indicator
usually takes the form of a dot, a half-circle, or the
number 1 placed at or near pin 1 of the device.
The BS1-IC has a “1” and a half-circle indicator on the
backside of the module. Additionally, Figure 1.1 above
indicates the pin numbering and labels.
All BS2 series modules have a half-circle indicator on the
topside of the module (see Figure 1.13). This indicates
that pin number one is the first pin counterclockwise from
the notch. The socket that accepts this 24-pin module also
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 25
Introduction to the BASIC Stamp
has a half-circle or notch on one end, indicating the correct
orientation. See Figure 1.14 for other examples.
Pin 1
Reference Notch
(pin 1 indicator)
23
2
4
5
Reference
Notch
Figure 1.13: Pin 1 Indicators
BS2-IC shown in the correct
orientation in relation to a 24-pin
socket.
24
1
3
Insert pin 1
here
Rev G
Note: The Half-Circle indicator is
also known as a Reference Notch
22
21
20
6
19
7
18
8
17
9
16
10
15
11
14
12
13
“Dot”
(Pin 1 indicator)
Insert pin 1
here
“1” printed on PC board
(Pin 1 indicator)
1
Page 26 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Figure 1.14: Additional
Examples of Pin 1 Indicators
(chip and socket shown in the
correct orientation in relation to
each other)
1: Introduction to the BASIC Stamp
BASIC Stamp Programming Connections
We suggest using a Parallax development board and cable for
programming BASIC Stamp modules. When these items are not available,
you may create your own board by duplicating the following diagrams
with your own circuits and cables.
Be very careful to follow these diagrams closely; it is quite common for
programming problems with the BASIC Stamp to be a result of a poorly
made custom cable or programming connections on your applications
board. With the programming connections for all the BS2 models, it is
possible to reverse a couple of wires and still get positive results using
some of the "connection" tests our Tech. Support team tries and yet you
still will not be able to communicate with the BASIC Stamp. It is vital that
you check your connections with a meter and verify the pin numbering to
avoid problems like this.
Figure 1.15: BS1 Programming
Connections with BS1 Serial
Adapter
Note: Though it is not shown, power
must be connected to the BS1 to
program it.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 27
Introduction to the BASIC Stamp
Figure 1.16: Programming and
Run-time Communication
Connections for all BS2 models.
Note: Though it is not shown, power
must be connected to the BASIC
Stamp to program it.
Also, the programming connections
are the same for the BS2p40.
Page 28 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
2: Quick Start Guide
Quick Start Introduction
This chapter is a quick start guide to connecting the BASIC Stamp to the
PC and programming it. Without even knowing how the BASIC Stamp
functions, you should be able to complete the exercise below. This
exercise assumes you have a BASIC Stamp and an appropriate
development board. For the latest Parallax development board selection
and documentation, go to www.parallax.com → Products → Development
Boards. For a more detailed introduction to the BASIC Stamp Editor
software, see Chapter 3.
Equipment Needed
•
•
•
•
BASIC Stamp module
Compatible carrier board and programming cable
Power supply (wall mount or battery) rated for your carrier board
PC running Windows® 2000/XP, with
o Quantity of RAM recommended for the OS
o 3 MB of hard drive space
o CD-ROM drive or Internet access
o Available port compatible with your carrier board and
cable (serial or USB)
Connecting and Downloading
1) If the BASIC Stamp isn't already plugged into your development
board, insert it into the socket. Refer to Figure 1.13 and Figure 1.14 on
page 26 to make sure that you orient it correctly. For a complete
listing of Parallax development boards for the various BASIC Stamp
modules, go to www.parallax.com and look for Development Boards
on the Products menu.
2) If you are using a Parallax development board, follow the directions
that came with it to connect the board to the appropriate port in your
computer. Figure 2.1 below shows the proper sequence for setting up
with a BS1 and a BS1 Carrier Board. Figure 2.2 on page 31 shows the
proper sequence to connect any BS2. Note: if you are using your own
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 29
Quick Start Guide
development board or a breadboard, carefully follow the
Programming Connections guidelines on page 27 before proceeding.
Figure 2.1: BS1-IC, BS1 Carrier
Board, and BS1 Serial Adapter
1) Insert the BASIC Stamp module
into its socket, being careful to
orient it properly.
2) Connect the 9-pin female end of
the serial cable to an available serial
port on your computer, then attach
the male end to the BS1 Serial
Adapter, Note: you cannot us a null
modem cable.
3) Plug the BS1 Serial Adapter into
the programming header on the BS1
Carrier Board.
4) Plug a 9 volt battery into the 9
VDC battery clip.
Page 30 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
2: Quick Start Guide
Alkaline Battery
Powercell
Figure 2.2: BS2-IC and Board of
Education
1) Insert the BASIC Stamp module
into its socket, being careful to
orient it properly.
3
2) Connect the 9-pin female end of
the serial cable to an available serial
port on your computer, and then
connect the male end to the Board
of Education. Note: you cannot use
a null modem cable.
4
or
15 14 Vdd 13 12
6-9VDC
9 Vdc
Battery
Red
Black
X4
Pwr
STA
MPS
C LA
SS
3) Plug in the 6-9 V 300mA centerpositive power supply into the barrel
jack.
in
TM
1
Sout
Sin
ATN
Vss
P0
P1
P2
P3
P4
P5
P6
P7
OR
4) Plug a 9 volt battery into the 9
VDC battery clip.
U1
Vin
Vss
Rst
Vdd
P15
P14
P13
P12
P11
P10
P9
P8
Vss
P1
P3
P5
P7
P9
P11
P13
P15
Vin
Vss
P0
P2
P4
P6
P8
P10
P12
P14
Vdd
X1
Reset
Vin
Vss
X3
P15
P14
P13
P12
P11
P10
P9
P8
P7
P6
P5
P4
P3
P2
P1
P0
X2
0
2
Vdd
X5
1
2
www.stampsinclass.com
Board of Education
© 2000-2003
1
3) Install and run the BASIC Stamp Editor software.
a) If using the Parallax CD, go to the Software → BASIC Stamp →
Windows section to locate the latest version. Click the Install
button and follow the prompts to install and run.
b) If using the Parallax website, go to www.parallax.com →
Downloads → Basic Stamp Software and look in the Software for
Windows section for the latest version. Click the Download icon
and follow the prompts to install and run.
c)
Test your PC’s connection to the BASIC Stamp by selecting Run →
Identify from the menu bar, as shown in Figure 2.3. If the BASIC
Stamp module is not found, check your power and cable
connections and retry.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 31
Quick Start Guide
Figure 2.3: Test your PC
connection to the BASIC Stamp.
Select Run → Identify
Verify that the BASIC Stamp was detected
on one of the COM ports.
4) Enter a $STAMP Directive into the Editor window by clicking on the
toolbar icon for the BASIC Stamp module you are using. (Hold the
cursor over the icons for flyover help labels.) The example below
shows the Stamp Directive that would be inserted for the BS2.
' {$STAMP BS2}
5) Enter a $PBASIC Directive into the Editor window with the toolbar
icon. For a BS1, you must use PBASIC 1.0. All BS2 series modules can
use PBASIC 2.0 or 2.5. The command set differences between PBASIC
2.0 and 2.5 are covered in Chapter 5.
Figure 2.4: Entering the $STAMP
and $PBASIC directives from the
toolbar
The examples shown would be used
for programming a BS2 module in
PBASIC 2.5
Click on the icon that corresponds to your
BASIC Stamp model to automatically place
the $STAMP directive in your program.
Click on the icon for the PBASIC language
version that is compatible with your BASIC
Stamp model.
You should now see both a $STAMP directive and $PBASIC directive
on your PC screen:
' {$STAMP BS2}
' {$PBASIC 2.5}
a) Note: These directives may be typed in from the keyboard, but
failure to type this line properly may cause the editor to fail to
recognize your BASIC Stamp during the next step.
Page 32 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
2: Quick Start Guide
6) Type the line DEBUG “Hello World!” below the compiler directives:
' {$STAMP BS2}
' {$PBASIC 2.5}
DEBUG "Hello World!"
7) Download this program into the BASIC Stamp. You may select Run
→ Run from the menu bar, press CTRL-R from the keyboard, or click
on the Run ► icon on the toolbar.
Figure 2.5: To run your program,
you may use the task bar menu or
the Run icon.
Selecting Run → Run
Using the Run toolbar icon
a) If the program is typed correctly, a progress bar window should
appear (perhaps very briefly) showing the download progress.
Then a Debug Terminal window should appear and display
"Hello World!"
Figure 2.6: Debug Terminal
displaying program output
b) If there is a syntax error in the program, the editor will highlight
the text in question and display an error message. Review the
error, fix the code and then try downloading again.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 33
Quick Start Guide
c)
If the error reported a connection problem with the BASIC Stamp,
make sure the first line of code indicates the proper module name
and verify the programming cable connections, module
orientation (in the socket) and that it is properly powered, then try
downloading again.
8) Congratulations! You've just written and downloaded your first
BASIC Stamp program! The "Hello World!" text that appeared on the
screen was sent from the BASIC Stamp, back up the programming
cable, to the PC.
Page 34 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
Introducing the BASIC Stamp Editor
This section describes the BASIC Stamp Editor for Windows version 2.2.
This software supports all 7 BASIC Stamp modules available as of
February 2005, and all 3 versions of the PBASIC programming language,
PBASIC 1.0, PBASIC 2.0, and PBASIC 2.5.
The Programming Environment
The BASIC Stamp Windows Editor, shown in Figure 3.1, was designed to
be easy to use and mostly intuitive. Those that are familiar with standard
Windows software should feel comfortable using the BASIC Stamp
Windows Editor.
Figure 3.1: BASIC Stamp Windows
Editor.
THE EDITOR WINDOW.
The editor window consists of the main edit pane with an integrated
explorer panel to its left, as shown above.
THE MAIN EDIT PANE.
The main edit pane can be used to view and modify up to 16 different
source code files at once. Each source code file that is loaded into the
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 35
Using the BASIC Stamp Editor
editor will have its own tab at the top of the page labeled with the name of
the file, as seen in Figure 3.2. The full file path of the currently displayed
source code appears in the title bar. Source code that has never been saved
to disk will default to “Untitled#”; where # is an automatically generated
number. A user can switch between source code files by simply pointing
and clicking on a file’s tab or by pressing Ctrl+Tab or Ctrl+Shift+Tab while
the main edit pane is active.
Figure 3.2: Example Editor Tabs.
Shown with 6 separate files open;
Title Bar shows current code’s file
path.
The status of the active source code is indicated in the status bar below the
main edit pane and integrated explorer panel. The status bar contains
information such as cursor position, file save status, download status and
syntax error/download messages. The example in Figure 3.3 indicates
that the source code tokenized successfully.
Figure 3.3: Status Bar beneath the
Main Edit Pane.
Each editor pane can be individually split into two views of the same
source code. This can be done via the Split button on the toolbar, pressing
Ctrl-L, or clicking and dragging the top or bottom border of the editor
pane with the mouse.
Once split, the top and bottom edit controls allow viewing of different
areas of the same source code; this can be handy when needing to keep
variable declarations or a particular routine in view while modifying a
related section of code elsewhere. Note that the Split button and Ctrl+L
shortcut act like a toggle function, splitting or un-splitting the edit pane.
Page 36 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
SPLIT WINDOW VIEW.
3: Using the BASIC Stamp Editor
Figure 3.4: The Split Edit Pane
Feature displaying the beginning
and end of a long program at the
same time.
SYNTAX HIGHLIGHTING.
NOTE: a complete list of reserved words
can be found in Appendix B.
Within the edit pane, BASIC Stamp source code files are displayed with
syntax highlighting. Syntax Highlighting applies designated colors and
character case (upper, lower, capitalized) to reserved words in the PBASIC
language . This happens automatically as you type. Table 3.1 shows the
default syntax highlighting settings for each syntax element.
If you copy and paste a program into a blank edit pane, select Run →
Syntax Check or click on the toolbar checkmark icon to activate the syntax
highlighting in that file. The syntax highlighting settings can be changed
or customized via the Preferences → Editor Appearance tab; for details see
the Setting Preferences section which begins on page 55. Source code can
be printed to paper with the active syntax highlighting (and in color if
using a color printer).
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 37
Using the BASIC Stamp Editor
Syntax Element
Command
Comment
Constant -Binary
Constant - Decimal
Constant - Hexadecimal
Constant – Predefined
Constant – String
Operators
Declaration
Directive, Conditional Compile
Directive, Editor
Directive, Target module
Input/Output Formatter
Selection
Search match
Variable modifier
Variable – predefined
Variable, type
Text Color
Blue
Green
Default
Default
Default
Purple
Red
Default
Default
Gray(Bold)
Teal (Bold)
Teal (Bold)
Navy
White on Navy
Lime on black
Default
Purple
Default
Character Case
Upper Case
No Change
No Change
No Change
No Change
Upper case
No Change
Upper case
Upper Case
Upper case
Upper case
Upper case
Upper case
No change
No change
Upper case
Upper case
Capitalize
Automatic line numbers can be enabled or disabled via the “Show Line
Numbers” checkbox on the Preferences → Editor Appearance tab. Line
numbers, when enabled, appear in a gutter (the gray area on the left of the
edit pane as shown in Figure 3.5). When printing, the line numbers may
be included if desired.
Table 3.1: Syntax Highlighting
Defaults for the PBASIC Scheme.
NOTE: The default edit pane has
a white background with black
characters.
AUTOMATIC LINE NUMBERING.
Figure 3.5: Automatic Line
Numbering appears in the gutter to
the left of the edit pane. Yellow
Bookmarks are visible on lines 5
and 9.
Bookmarks can be enabled or disabled via the “Show Bookmarks”
checkbox on the Preferences → Editor Appearance tab. The bookmarks
appear in the gutter as small numbered icons, providing a way to mark
lines or sections of code that you need to navigate to quickly or repeatedly.
You can define up to nine bookmarks by clicking on the gutter where you
want one placed, or by pressing Ctrl+B when the cursor is on the desired
line. You can instantly navigate to any defined bookmark by pressing
Ctrl+(#) (where # can be the 1 through 9 keys) or by selecting Go To
Page 38 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
BOOKMARKS.
3: Using the BASIC Stamp Editor
Bookmark from either the Edit menu or from the shortcut menu (rightclick) in the edit pane.
EDITING YOUR CODE.
Table 3.2: Keyboard Shortcuts for
Editing and Navigation Functions.
You can navigate through and edit your code in the edit pane with
keyboard shortcuts, most of which will be familiar to Windows users.
Shortcut Key
Ctrl+A
Ctrl+B
Ctrl+(#)
Ctrl+C
Ctrl+F
Ctrl+L
Ctrl+N
Ctrl+V
Ctrl+X
Ctrl+Y
Ctrl+Shift+Y
Ctrl+Z
Ctrl+Shift+Z
Tab
Shift+Tab
F3
F4
Ctrl+F4
Ctrl+Home
Ctrl+End
Ctrl+PageUp
Ctrl+PageDown
Ctrl+CursorUp
Ctrl+CursorDown
F5
Editing and Navigation Functions
Function
Select all text in current source code
Set or clear bookmark on current source code line
Go to bookmark #, where # can be 1 through 9
Copy selected text to the clipboard
Find or replace text
Split or un-split edit pane
Insert line
Paste text from clipboard to selected area
Cut selected text to the clipboard
Delete current line of code
Delete from cursor to end of current line
Undo last action (unlimited)
Redo last action (unlimited)
Indent block (Inserts tab or space characters)
Outdent block (Deletes tab or space characters)
Find text again
Replace current found selection
Perform replace and find next
Jump to top of file
Jump to end of file
Jump to top of screen
Jump to bottom of screen
Move source view up one line without moving cursor
Move source view down one line without moving cursor
Open Preferences window
Some editing functions, specifically Cut, Copy, Paste, and Find/Replace,
can also be accessed from the edit pane’s shortcut menu (by right-clicking
in the edit pane).
THE FIND/REPLACE WINDOW.
The Find/Replace window allows you to set several search parameters.
Match whole or partial words, match case, and match with wildcard
options can be used singly or together. You can begin your search at the
cursor or at the top or bottom of the selection or the entire file, and search
in the forward (downward) or backward (upward) direction. You may
replace a single instance of a given item or all instances at once. Recent
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 39
Using the BASIC Stamp Editor
Find and Replace items are saved in the Find: and Replace: field’s dropdown lists.
Figure 3.6: The Find/Replace
Window.
The Find/Replace window will stay visible when using the Find Next and
Replace options for quick and convenient source code editing. Using the
Replace All function, however, will close the Find/Replace window and
perform the designated find/replace operation.
The integrated explorer panel to the left of the main edit pane is divided
in to four portions: the Recent, Directory, File and Filter lists. The upper
portion is the Recent list, a drop-down list of default, favorite, and recently
visited directories.
If you select a directory from the Recent list drop down field, the
integrated explorer will automatically navigate to that directory. The
button to the left of the Recent list allows you to limit the Directory list
display below it to only the directories that are in the Recent list. This
makes it easy to find your commonly used source code directories among
a large set of directories and local and network hard drives. The Recent
list button behaves like a toggle switch: 1) selecting it switches to the
“Show Recent folders only” mode, 2) selecting it again switches back to
the “Show all folders” mode.
Page 40 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
THE INTEGRATED EXPLORER PANEL.
3: Using the BASIC Stamp Editor
Figure 3.7: The Integrated Explorer
Panel’s Recent list (top), Directory
list (middle), and File list (bottom).
THE DIRECTORY LIST.
The Directory list, right below the Recent list, displays drives and
directories in a hierarchical tree fashion. If a directory is selected, the
Folders list displays the files in that directory.
THE FILE LIST.
The File list, below the Directory list, displays all the files in the selected
directory that match the selected filter (from the Filter list at the bottom.
see Figure 3.8). You can select one or more files from this list and doubleclick, or drag-and-drop them over the editor pane, to open those files.
OPEN FROM... AND SAVE TO... OPTIONS.
You may also open files with the Open From... option by selecting File →
Open From, or by pressing Ctrl+Shift+O. This allows quick access to any
directory for the default and favorite directories set within Preferences (see
page 60) as well as any recently used directory. The Save To... option
works similarly; select File → Save To or press Ctrl+Shift+S. These
features can be very helpful if you organize your files in many different
directories.
THE FILTERS LIST.
The Filter list at the bottom of the explorer panel (Figure 3.8), is a dropdown list of file extension filters to apply to the File list. It works just like
the “Save as type:” field of a standard Open or Save dialog.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 41
.
Using the BASIC Stamp Editor
Figure 3.8: The Filter List found at
the bottom of the Integrated
Explorer Panel.
The BASIC Stamp Editor automatically associates BASIC Stamp source
code file types (.bs1, .bs2, .bse, .bsx, .bsp, .bpe, and .bpx) with itself. This
feature can be configured through automatic prompts or through the
Preferences → Files & Directories tab. Also, when using any Explorershell for file browsing, right-clicking on a BASIC Stamp source code file
provides you with an Open With Stamp Editor option.
The integrated explorer panel can be resized via the vertical splitter bar
that separates it and the edit pane. The Directory list and File list can be
resized via the horizontal splitter bar that separates them. The integrated
explorer can also be hidden or shown via the Explorer toolbar button, by
pressing Ctrl+E, or by resizing it to zero width using the vertical splitter
bar.
Table 3.3 lists keyboard shortcuts for several file functions.
File Functions
Shortcut Key
Ctrl+E
Ctrl+L
Ctrl+O
Ctrl+Shift+O
Ctrl+S
Ctrl+Shift+S
Ctrl+P
Ctrl+Tab
Ctrl+Shift+Tab
Function
Show/hide explorer panel
Show/hide split view in edit pane
Open a source code file into edit pane
Open a source code file from a recent directory into edit pane
Save current source code file to its current location on disk
Save current source code file to a recent directory on disk
Print current source code
Switch to next open file page
Switch to previous open file page
Page 42 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 3.3: Keyboard Shortcuts for
File Functions.
3: Using the BASIC Stamp Editor
Compiler Directives
COMPILER DIRECTIVES .
The BASIC Stamp Editor supports all of the BASIC Stamp models, and all
versions of the PBASIC programming language. Compiler directives must
be placed in each program to indicate the desired BASIC Stamp model and
language version. In addition, it is sometimes useful to target a given
program to a particular communication port. The Directive menu contains
options for setting the $STAMP, $PBASIC, and $PORT directives. Since
the $STAMP and $PBASIC directives are used most often, they are most
easily inserted or modified with the toolbar buttons, as shown in Figure
3.9.
Figure 3.9: Toolbar icons make it
easy to insert or modify $STAMP
and $PBASIC directives directly in
your program.
THE
$STAMP DIRECTIVE.
FORMAT OF THE $STAMP DIRECTIVE.
A $STAMP directive is required in each PBASIC program. The editor
determines which BASIC Stamp model to target for compiling and
downloading based on this directive. Any code that is missing the
$STAMP directive, but whose filename contains a known BASIC Stamp
extension (.bs1, .bs2, .bse, .bsx, .bsp, .bpe, .bpx) will be recognized by that
extension and an appropriate $STAMP directive will be added
automatically when you run, tokenize, view the memory map or
download the program. If there is no file extension present, an error
message will prompt you to enter a $STAMP directive.
You may choose to manually type the $STAMP directive into the program
from the keyboard. This line should be entered into your code on a line by
itself, usually near the top. Note that the directive appears on a comment
line, as indicated by the apostrophe (').
'
'
'
'
'
'
'
{$STAMP
{$STAMP
{$STAMP
{$STAMP
{$STAMP
{$STAMP
{$STAMP
BS1}
BS2}
BS2e}
BS2sx}
BS2p}
BS2pe}
BS2px}
'This
'This
'This
'This
'This
'This
'This
indicates
indicates
indicates
indicates
indicates
indicates
indicates
to
to
to
to
to
to
to
use
use
use
use
use
use
use
a
a
a
a
a
a
a
BASIC
BASIC
BASIC
BASIC
BASIC
BASIC
BASIC
Stamp
Stamp
Stamp
Stamp
Stamp
Stamp
Stamp
1 module
2 module
2e module
2sx module
2p module
2pe module
2px module
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 43
Using the BASIC Stamp Editor
If you choose to type the $STAMP directive, care must be taken, or it will
not be recognized. The directive itself must be enclosed in curly braces,
{…}, not parentheses (...) or square brackets [...]. There should not be
any spaces between the dollar sign ($) and the word STAMP; however, the
directive may contain additional spaces in certain other areas. For
example:
'
{
$STAMP
BS2
EXTRA SPACES ARE ALLOWED IN CERTAIN
AREAS.
}
-- or -' {$STAMP
BS2}
-- and -' {$STAMP
BS2
}
are all acceptable variations. However:
' {$
STAMP
BS2}
-- and -' {$STAMPBS2}
are not acceptable and will be ignored. If one of the above two lines were
entered into the source code, the editor would ignore it and, instead, rely
on the extension of the filename to determine the appropriate model.
The $STAMP directive is read and acted upon by the BASIC Stamp
Windows Editor any time a source code file is loaded, tokenized,
downloaded (run) or viewed in the Memory Map.
In some cases you may wish to write a program that can run on multiple
BASIC Stamp models. In this case, conditional compile directives can be
employed that will cause the editor to determine which Basic Stamp
model is detected, and then download only those program elements
applicable to that model. Many of the demo programs in Chapter 5 use
this technique. To read about conditional compilation, see the Advanced
Compilation Techniques section which begins on page 68.
PROGRAMS FOR MULTIPLE BASIC STAMP
MODELS – CONDITIONAL COMPILE.
The $PBASIC directive allows you to indicate which version of the
PBASIC language to use. At the time of this printing, the options are 1.0,
2.0 and 2.5. If no $PBASIC directive is present in the program, version 1.0
is assumed for BS1 module source code, and version 2.0 is assumed for
THE $PBASIC DIRECTIVE.
Page 44 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
any BS2 model source code. A $PBASIC directive is required to use
version 2.5, which is compatible with all BS2 models.
PBASIC 2.5 has enhanced syntax options for several commands, as well as
some additional commands not available in PBASIC 2.0. Table 3.4 shows
the number of PBASIC commands that are available in each version of the
PBASIC language, on each BASIC Stamp model. Details about the syntax
differences among the three versions of PBASIC are denoted by icons in
the margins of Chapters 4 and 5; also refer to Table 5.1 on page 124 and
individual command syntax descriptions.
Table 3.4: Number of Available
Commands for each BASIC
Stamp Model with each version
of the PBASIC language .
PBASIC 1.0
PBASIC 2.0
PBASIC 2.5
BS1
32
-
BS2
37
42
BS2e
40
45
BS2sx
40
45
BS2p
56
61
BS2pe
56
61
BS2px
58
63
A categorical listing of all PBASIC commands is included at the beginning of Chapter 5,
followed by detailed descriptions of each command in alphabetical order.
Note that the syntax-highlighting feature of the BASIC Stamp Editor will
also adjust to the language version indicated by the $PBASIC directive.
The best way to select the $PBASIC directive is to use the toolbar icons, as
was shown in Figure 3.9. Like the $STAMP directive, you must use care if
you choose to type it in by hand. The syntax is:
' {$PBASIC 1.0}
' {$PBASIC 2.0}
' {$PBASIC 2.5}
'Default when a BASIC Stamp 1 module is detected
'Default when any BASIC Stamp 2 module is detected
'Required for PBASIC 2.5 command set & enhanced syntax
If you try to run a program that contains command syntax specific to
PBASIC 2.5 without including the corresponding compiler directive, you
will probably get an error message. In this case, insert a $PBASIC 2.5
directive and try running the program again.
THE $PORT DIRECTIVE.
The optional $PORT directive allows you to indicate a specific PC
communications port through which to download a program to a BASIC
Stamp module. The syntax is as follows:
' {$PORT COM#}
where # is a valid port number. When any PBASIC program containing
this directive is downloaded, all other ports will be ignored. This directive
is especially convenient when using two of the same BASIC Stamp models
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 45
Using the BASIC Stamp Editor
(such as two BS2s) on two ports and you have two different PBASIC
programs to download (one to each BS2). Without this directive,
developing and downloading in this case would be a tedious task of
always answering the "which BASIC Stamp?" prompt.
The $PORT directive can be automatically inserted or modified by
selecting the appropriate port from the Directive → Port menu. The COM
ports listed in the Directive → Port menu are automatically updated any
time a change is made to the exiting computer hardware or to the available
ports list. See the Setting Preferences section which begins on page 55 for
more information.
Special Functions
The Identify function will identify which BASIC Stamp model, if any, is
detected on any available communications port. This information is
displayed in the Identification window (Figure 3.10), which can greatly aid
in troubleshooting your connection to your BASIC Stamp module.
Activate this function by selecting Run → Identify, by pressing Ctrl-I, or
pressing F6.
THE IDENTIFICATION FUNCTION .
Figure 3.10: The Identification
Window.
The Port column shows the available ports (those that the BASIC Stamp
Editor is trying to access). You can modify the available Port List by
clicking on the Edit Port List button. Modifying this list only affects which
ports the BASIC Stamp Editor tries to use; it does not affect which serial
ports are installed on your computer. It is recommended that you delete
all known modem ports and any problematic ports from this list.
Page 46 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
The Device Type column shows the model of BASIC Stamp found on the
respective port. For example, in Figure 3.10 above, the BASIC Stamp
Editor found a BS2 on COM port 1 and a BS2sx on COM port 4.
The Version column displays the firmware version number of the BASIC
Stamp module that was found.
NOTE: when using a BS1 Serial
Adapter, the Loopback column of the
Identification window should always
indicate “No”.
The Loopback column indicates whether or not a loopback connection was
found on the port. The loopback connection is created by BASIC Stamp
development boards, such as the Board of Education, across serial port
pins 6 and 7 (of a DB9). A “Yes” in this column is an indication that the
serial port and serial cable are properly connected to a BASIC Stamp
development board. Note that the Loopback column should always
indicate “No” when using a BS1 Serial Adapter, regardless of whether or
not the adapter is properly connected to a BASIC Stamp development
board.
The Echo column indicates whether or not a communication echo was
detected on the port’s transmit and receive pins (pins 2 and 3). All BASIC
Stamp 2 models create this echo naturally, even without power. BASIC
Stamp 1 modules do not create this echo. A “Yes” in this column is an
indication that the serial port and serial cable are properly connected to a
BASIC Stamp 2 (or higher) module, and if using a BASIC Stamp
development board, it’s an indication that the module is properly
connected to the development board.
For all BASIC Stamp 2 models, the Loopback and Echo columns are great
for doing some simple connection diagnosis when using a serial port. For
example, a Yes in both columns indicates the serial port and serial cable
are properly connected and that the BASIC Stamp is properly inserted into
its socket. See Table 3.5 below. Note that the Loopback column does not
give reliable results when using a USB to serial adapter, or a USB-based
development board. Usually this is not an error, and the Loopback status
can simply be ignored.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 47
Using the BASIC Stamp Editor
Loopback
Echo
Yes
Yes
Yes
No
No
Yes
No
No
Interpretation
Serial port and serial cable properly connected. BASIC Stamp
properly inserted into socket. If no BASIC Stamp is detected, it is
probably because the BASIC Stamp is not connected to power.
Other causes could be: 1) low battery, 2) Reset pin of BASIC Stamp
is connected to Vdd (it should be left disconnected), 3) the BASIC
Stamp is damaged or 4) there is some other type of communication
error (software or hardware).
Serial port and serial cable properly connected to the development
board. BASIC Stamp improperly inserted into socket (i.e.: inserted
backwards or not inserted at all).
Serial port and serial cable may be improperly connected, or you
may not be using a standard BASIC Stamp development board.
The Echo indicates there may be a BASIC Stamp properly
connected to the port (the Loopback is not required for successful
connection) or there may be another device connected to the serial
port.
Serial port and serial cable are not properly connected, or not
connected at all, to the BASIC Stamp 2 (and higher) modules.
Could also be an indication of a serial port hardware/software
problem. When using a BS1 Serial Adapter, this Loopback and
Echo is normal and expected.
Selecting the “Ignore BS1 Modules unless downloading BS1 source code”
checkbox at the bottom of the Identification window optimizes
identification speed. All BS2 models can be identified very quickly. For
BASIC Stamp 1 modules, the identification process can take as much as
five seconds per communications port. Since the Identification function
checks all available serial ports for any possible model of BASIC Stamp,
the five-second timeout for BS1’s can be very inconvenient, especially if
you are not using a BS1.
Table 3.5: Using Loopback and
Echo to troubleshoot your serial
port (DB9) connection.
NOTE: When using a USB port,
the Loopback column does not
give reliable results. Usually this is
not an error and the Loopback
status can be ignored.
SPEED UP IDENTIFICATION WITH THE
“IGNORE BS1 MODULES” CHECKBOX.
When this checkbox is checked, the Identification function will not attempt
to locate BS1 modules, and thus saves time. If, however, you are
downloading BASIC Stamp 1 code, the Download function will attempt to
locate BS1 modules regardless of the setting of this checkbox. This feature
can also be found and modified via the Preferences → Editor Operation
tab.
Like the Identification function, the Download function provides
information to help guide you through the downloading process. After
entering the desired source code in the editor window, you may run it in
one of three ways: select Run → Run, press Ctrl+R on the keyboard, or
click on the “►” toolbar icon. This will tokenize and download the code
Page 48 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
THE DOWNLOAD FUNCTION .
3: Using the BASIC Stamp Editor
to the BASIC Stamp module (assuming the code is correct and the BASIC
Stamp is properly connected). The Download Progress window looks
similar to the Identify window with the exception of the additional
Download Status progress bar, and the indicator LED by the port
transmitting the data.
Figure 3.11: The Download
Progress Window.
If any errors occur, such as communication failure or inability to detect a
BASIC Stamp module, you will be prompted appropriately. One possible
error occurs when the BASIC Stamp your PBASIC program is targeting
does not appear to be connected to the PC (see Figure 3.12). This may be
caused, for example, by opening up a BASIC Stamp 1 program (usually
has a .bas or .bs1 extension) and trying to download it to a BASIC Stamp 2
module, instead.
Figure 3.12: A Download Error
message.
When this happens, you’ll be prompted to correct the situation, quickly
done by clicking on the BS2 button (if you really intended to download to
the BS2 in the first place). Keep in mind that programs written for one
BASIC Stamp model may not function properly on a different BASIC
Stamp model. Click on the More Info button for more detail. NOTE: If
you select the BS2 button, as in this example, the editor will modify the
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 49
Using the BASIC Stamp Editor
$STAMP directive in the program, notify you of this change and what it
means, and then will try to download to the BS2.
Another possibility is having two or more of the same BASIC Stamp
model connected to the PC. In this case, the editor will prompt you for
clarification as to which BASIC Stamp module you want to download to.
In this case using a $PORT directive in your code will save you some
tedium in repeatedly responding to such prompts.
The BASIC Stamp Editor also features a Memory Map that displays the
layout of the current PBASIC program. Type Ctrl+M, or press F7, to
activate this window.
MEMORY MAP FUNCTION.
When you activate the Memory Map, the editor will check your program
for syntax errors and, if the program’s syntax is okay, will present you
with a color-coded map of the RAM and EEPROM. You’ll be able to tell at
a glance how much memory you have used and how much remains.
Figure 3.13: Memory Map for
Demo Program DATA.bs2.
The Memory Map is divided into two sections, the RAM map and the
EEPROM map. The RAM map shows how much of each register has been
allotted to program variables. The RAM legend details how much is used
by I/O Pins, Word, Byte, Nibble and Bit variables, and how much is
unused.
Page 50 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
THE RAM MAP.
3: Using the BASIC Stamp Editor
THE EEPROM MAP.
The EEPROM map is shown in two scales. The main view is the detailed
EEPROM map, which displays the data in hexadecimal format in each
location. The condensed EEPROM map is the vertical region on the left
that shows a small-scale view of the entire EEPROM; the red square over it
corresponds to the scroll bar handle in the detailed EEPROM map and
indicates the portion of the EEPROM that is currently visible in the
detailed EEPROM map.
Checking the Display ASCII checkbox switches the detailed EEPROM
display from hexadecimal to ASCII. In this program, the textual data can
be read right off the EEPROM map when using this option.
Two important points to remember about this map are: 1) it only indicates
how your program will be downloaded to the BASIC Stamp module; it
does not "read" the BASIC Stamp memory, and 2) for all BS2 models, fixed
variables like B3 and W1 and any aliases do not show up on the memory
map as memory used. The editor ignores fixed variables when it arranges
automatically allocated variables in memory. Remember, fixed and
allocated variables can overlap.
THE DEBUG TERMINAL.
The Debug Terminal window provides a convienent display for data
received from a BASIC Stamp during run-time, and also allows for the
transmission of characters from the PC keyboard to the BASIC Stamp. The
Debug Terminal is automatically opened and configured when a PBASIC
program, containing a DEBUG command, is downloaded. You can
manually open a Debug Terminal one of three ways: select
Run → Debug → New, press Ctrl+D on the keyboard, or click on the
Debug Terminal toolbar button. Up to four (4) Debug Terminals can be
open at once (on four different ports) and all can be left open while editing
and downloading source code.
Figure 3.14 below shows the demo program DEBUG_DEBUGIN.bs2 in the
edit pane, and the Debug Terminal that opens when this program is run.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 51
Using the BASIC Stamp Editor
Figure 3.14: Demo program using
the Debug Terminal
The text in the Debug Terminal’s Receive pane (blue area) prompts the
user to enter a number into the Transmit pane (white area) . After typing
the number 10 and pressing Enter, the Receive pane displays the number
in decimal, hexadecimal, and binary format as dictated by the program
(Figure 3.15).
Figure 3.15: Debug Terminal
output after entering a number.
The fields across the top of the Debug Terminal window allow
configuration of the communication port settings. These fields will be
automatically configured and disabled if the Debug Terminal was
Page 52 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
PORT SETTINGS AND STATUS.
3: Using the BASIC Stamp Editor
automatically opened by the editor, however, if manually opened, these
fields will be enabled to allow manual configuration. The signal status
LEDs turn bright green when activity on the indicated port line is
detected. The signal checkboxes (DTR and RTS) can be selected to set or
clear the respective output line on the port.
The Echo Off checkbox (bottom of window) causes the Receive pane to
throw away the characters that arrive in the port’s receive buffer
immediately after transmitting characters from the transmit buffer. This
produces a cleaner Receive pane display for interactive programs such as
the example above. Keep in mind, however, that this feature does not
verify that the character it throws away is actually a match to a character
that was just transmitted (because data collisions on the port can cause
echoed characters to be garbled). You should only use the Echo Off
feature in situations where it is required, as it may result in a strange
display in certain applications.
KEYBOARD SHORTCUTS FOR CODING
FUNCTIONS.
Table 3.6: Coding Function
Keyboard Shortcuts.
There are keyboard shortcuts for several coding functions, some of which
are unique to the BASIC Stamp Editor.
Shortcut Key(s)
Ctrl+J
F6 or Ctrl+I
F7 or Ctrl+T
F8 or Ctrl+M
F9 or Ctrl+R
F11 or Ctrl+D
F12
Ctrl+1, Ctrl+2,
Ctrl+3, Ctrl+4
Ctrl+`
ESC
HELP FILES.
Coding Functions
Function
Show code templates.
Identify BASIC Stamp firmware.
Perform a syntax check on the code and display any error
messages.
Open Memory Map window.
Tokenize code, download to the BASIC Stamp and open
Debug window if necessary.
Open a new Debug window.
Switch to next window (Editor, Debug #1, Debug #2, Debug #3
or Debug #4)
Switch to Debug Terminal #1, Debug Terminal #2, etc. if that
Terminal window is open.
Switch to Editor window.
Close current window.
The BASIC Stamp Editor includes searchable, indexed help files. Access
Help by selecting Help → Contents or Help → Index. Context sensitive
help (highlighting a word in the editor and pressing F1 key) is also
supported. The help file can remain open in a separate window while
using the BASIC Stamp Editor; simply press Alt+Tab to toggle back and
forth between the editor and the Help window.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 53
Using the BASIC Stamp Editor
Figure 3.16: The Help file contains
the complete PBASIC syntax
documentation.
The current help files contain the entire PBASIC syntax documentation. In
addition, the example demo code programs that appear after most
command descriptions in Chapter 5 are automatically placed in default
directories during the BASIC Stamp Editor v2.2 installation. These
programs can be accessed via hyperlinks within the help file.
NOTE: The BASIC Stamp Editor Help file requires Microsoft's HTML
Help utility and Internet Explorer 4.0 or above (IE 6.0 recommended). The
proper version of HTML Help is included with Windows 2000 and
Windows XP. On other versions of Windows you may have to install or
upgrade your HTML Help utility to properly view the Stamp Editor’s
on-line help. The HTML Help upgrade program (hhupd.exe) is included
as part of the BASIC Stamp Editor setup program and the editor will
automatically prompt you to run it if it determines you need to upgrade.
You can download the latest version of Internet Explorer from Microsoft’s
web site at www.microsoft.com.
Page 54 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
HELP FILES REQUIRE MICROSOFT’S HTML
HELP UTILITY.
3: Using the BASIC Stamp Editor
TIP OF THE DAY.
The Tip of the Day function displays a new message each time you run the
BASIC Stamp Editor. There are many useful tips, and you may browse
through them any time with the Next Tip and Previous Tip buttons. You
may also use the Edit Tips option to change the contents of any tip. All
tips are contained in a single file, named Stamp_Tips.txt, that is stored in
the editor’s installation directory, usually a path similar to
C:\Program Files\Parallax Inc\Stamp Editor v2.2.
Figure 3.17: Tip of the Day #24.
You can turn this feature off by unchecking the Show Tips on Startup box
at the bottom of the window. To access it again, choose Help → Tip of the
Day from the menu bar.
Setting Preferences
The BASIC Stamp Editor allows the user to set preferences for the
appearance and operation of many aspects of the application. Select
Edit → Preferences, press F5 or click on the Preferences toolbar button to
open the Preferences window, where you will see these options organized
under 6 tabs. Each tab has a Restore Defaults button in case you make a
royal mess of things.
EDITOR APPEARANCE PREFERENCES.
Under the Editor Appearance tab (Figure 3.18), you can set the font size in
the edit pane. The other text attributes, such as background and
foreground color, character case, and bold, italic and underline, are
controlled by the Syntax Highlighting scheme. There are 3 predefined
schemes, and you may also create a custom scheme. Please note that the
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 55
Using the BASIC Stamp Editor
preferences are specific to the editor, and are not saved as part of any
BASIC Stamp program that you may have open while setting preferences.
Figure 3.18: The Editor Appearance
Tab under Edit → Preferences.
The default font size for the edit pane is 10 point, but there are 12 fixed
options ranging from 8 to 40 point. The Editor Font size setting and all the
other text attribute settings under this tab will not affect the text in the
Debug Terminal.
The default scheme is the “PBASIC” scheme, with the syntax highlighting
text attributes described above in Table 3.1. The “plain text” scheme is just
that – the default foreground and background for all entered text, with no
other attributes applied. The “simple” scheme is the same as the “plain
text” scheme, except comments appear in green. Both the plain text and
simple schemes use the PBASIC scheme defaults for selected text.
Page 56 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
SYNTAX HIGHLIGHTING SCHEMES.
3: Using the BASIC Stamp Editor
CUSTOMIZED SYNTAX HIGHLIGHTING.
To create a custom scheme, select a default scheme you wish to modify,
and click on the Copy Scheme button. Then, select (highlight) an element
within the Syntax Element list, and apply new Text Attributes with the
checkboxes and drop-down menus to the right. As you try various text
attributes and color combinations, the Show Preview Example checkbox
lets you audition your custom scheme without closing the Preferences
window.
The BASIC Stamp Editor supports one custom scheme at a time. It can be
modified indefinitely, but it cannot be copied. If you again copy a default
scheme, you will be asked to confirm that you wish to overwrite your
current custom scheme.
Under this tab, you will also find checkboxes that allow you to show or
hide bookmarks, line numbers, the overwrite cursor, and the toolbar.
EDITOR OPERATION PREFERENCES.
AUTO INDENTING / UNINDENTING.
TAB CHARACTER.
Under the Editor Operation tab (Figure 3.19), you may set preferences for
automatic indentation and tab behavior.
The Auto Indent on Enter option makes it easy to indent nested loops to
make code easier to read. The Auto Unindent option enables quick
reversal of an indented line by simply using the backspace key, provided
that the cursor is to the left of the first character on the line.
The editor lets you choose whether a tab character or spaces are inserted
into source code whenever you press the Tab key. The default setting,
insert space characters upon Tab key presses, is recommended because it
enforces the intended formatting regardless of what editor you use to view
the code later.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 57
Using the BASIC Stamp Editor
In addition to the actual character used for the Tab key, there are three
behaviors of tabbing employed by the editor: Smart Tabs, Fixed Tabs and
Fixed plus Smart Tabs.
TAB BEHAVIOR.
Figure 3.19: The Editor Operation
Tab under Edit → Preferences.
Smart Tabs (Figure 3.20) cause the tab key to move the cursor to a position
that is aligned with the nearest break between words in nearby lines above
the current line. It has the effect of providing a somewhat intuitive, auto
adjusting behavior based entirely on how you have aligned previous lines.
SMART TABS.
Fixed Tabs (Figure 3.21) cause the tab key to move the cursor to the
position indicated by the Fixed Tab Positions field. If the position is
already beyond the end of the Fixed Tab Positions list, it moves by a
multiple of the distance between the last two positions in that list. For
example, with Fixed Tabs set, the default Fixed Tab Positions list will
FIXED TABS.
Page 58 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
make the Tab key move the cursor to positions, 3, 5, 7, 9 and 11, then
afterwards, 13, 15, 17, 19, etc. (a multiple of two (11 – 9 = 2) after the last
listed position.
FIXED PLUS SMART TABS.
The last option is a mixture of the first two, Fixed plus Smart Tabs
(Figure 3.22); it is the default and recommended setting. Fixed plus Smart
Tabs will cause the tab key to move the cursor to the position indicated by
the Fixed Tab Positions field, or if the position is already beyond the end
of that list, it reverts to Smart Tabs behavior. This setting, combined with
a carefully configured Fixed Tab Positions field, allows for a fixed level of
indenting on the left side of the source code (for executable code blocks),
with very flexible indenting to the right of executable code (for comments
that appear to the right of code). The default settings provide a quick,
single-key method of indenting up to five (5) levels of executable code and
easy alignment of multiple lines of comments to the right of that code.
Figure 3.20: Smart Tabs.
Figure 3.21: Fixed Tabs.
Figure 3.22: Fixed plus Smart Tabs.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 59
Using the BASIC Stamp Editor
The Fixed Tab Positions list is used to provide a list of desired fixed tab
positions (used with Fixed Tabs or Fixed plus Smart Tabs options). The
list can be a single number, or a list of comma separated numbers in
ascending order. The allowable range is 2 to 512 and the list size is
virtually unlimited. When multiple values are entered, the difference
between the last two values will be used to set tab positions beyond the
last position. For example, in the default list, the last two positions are 9
and 11; resulting in further tab positions of 13, 15, 17, etc. (multiples of 2
after the last specified position). Since source code is usually indented by
multiples of two (2) spaces, the default list of 3, 5, 7, 9 and 11 is
recommended.
THE FIXED TAB POSITIONS LIST.
The Default Com Port setting allows you to specify which COM port to
download through. If you specify a specific port here, the Identification
window will report that it is “ignoring” other known ports. This can be
selectively overridden by placing a $PORT directive in the program. If
this setting is left on “AUTO”, the default, the editor will open and scan all
known ports for the correct BASIC Stamp. The button to the right, labeled
‘...’, opens the a window allowing the known port list to be edited.
Modifying the known port list only affects which ports the BASIC Stamp
Editor tries to use; it does not affect which serial ports are installed on
your computer. It is recommended that you delete all known modem
ports and any problematic ports from this list.
DEFAULT COM PORT.
For an explanation of the Default Project Download Modes, see Table 3.7
on page 70. This is part of a discussion on BASIC Stamp Projects in the
Advanced Compilation Techniques beginning on page 68, below.
Selecting the “Ignore BS1 Modules unless downloading BS1 source code”
checkbox optimizes identification speed by attempting to locate BS1
modules only if you are downloading BASIC Stamp 1 code. This feature
can also be activated via the Identification or Download window.
Under the Files and Directories tab (Figure 3.23), you can set preferences
for saving and accessing files, as well as automatically creating backup
copies.
Page 60 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
THE FILES AND DIRECTORIES TAB.
3: Using the BASIC Stamp Editor
Figure 3.23: The Files and
Directories Tab under
Edit → Preferences.
BACKUP COPY.
Check the “Create backup copy” option to cause the editor to
automatically create a backup copy of any file that is being re-saved under
the same name. The backup file will be stored in the same directory and
named the same as the existing file, but with a .bak extension appended to
the existing extension. For example, “test.bs2” becomes “test.bs2.bak” and
then the new file called “test.bs2” is created from the source code being
saved. Note: the .bak files will not appear in the integrated explorer’s file
window unless you change the Filter list to show All Files (*.*).
FILE ASSOCIATIONS.
BASIC Stamp source code file types (.bs1, .bs2, .bse, .bsx, .bsp, .bpe, .bpx)
can be associated with the BASIC Stamp Editor. Check the “Verify at
startup” option to have the editor verify the proper associations each time
it is started. The “Associated files launch into” option changes the way
Windows behaves when you open BASIC Stamp source code from any
Explorer-shell. Choosing “Single Editor” causes all programs to open up
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 61
Using the BASIC Stamp Editor
into a single BASIC Stamp Editor, including an editor that is already
running. The “Multiple Editors” option will cause a new BASIC Stamp
Editor to open each time you open an associated BASIC Stamp file from
any Explorer-shell.
Also, by associating BASIC Stamp source code with the editor, Windows
will provide an “Open With Stamp Editor” option when right-clicking on
that source code from any Explorer-shell.
OPEN WITH STAMP EDITOR OPTION.
The “New file template” field allows you to specify a file to load each time
the File → New function is selected. The file will be loaded into the new
edit page, but the name will be set to “Untitled#”; where # is an
automatically generated number. This feature provides a convenient way
to start every new source code project with a specified code template of
your choosing. Note that once this feature is set, you may hold down the
Shift key while selecting File → New, or clicking the New File toolbar
button, to suppress the loading of the code template and thus end up with
a blank edit page.
NEW FILE TEMPLATE FEATURE.
The “Upon startup, initial directory is” field affects what directory is
initially selected in the integrated explorer and the Open and Save As
dialog boxes when the editor is started. The default is “Last Used,”
meaning the initial directory will be that which was most recently used by
the editor. If this setting is changed to “Set Via Shortcut” the editor will
initially view the directory indicated by the “Start in” field of the
Windows shortcut that launched the editor. The other options include the
default module directories and favorite directories.
INITIAL DIRECTORY ON STARTUP.
The Module Directories list contains a list of module-specific directories
that are called the “default module directories.” Upon installation of the
BASIC Stamp Editor software, the PBASIC source code examples in this
text are copied to the installation folder and organized into appropriate
subfolders. If the default installation folder is used during software
installation, the source code files will be copied to a path similar to:
C:\Program Files\Parallax Inc\Stamp Editor 2.2\BS1, BS2, BS2sx..., etc.
The BASIC Stamp Editor automatically sets its default directories to point
to these source code examples, making them immediately available via the
File → Open From… and File → Save To... menus as well as the Recent list
in the integrated explorer panel.
MODULE DIRECTORIES.
Page 62 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
You may use the Clear and Browse… buttons under the Module
Directories list to select new default directory locations for each model of
BASIC Stamp. These new folders will then appear as options when you
use the File → Open From... and File → Save To... menus as well as the
Recent list in the integrated explorer panel.
Note that if you are upgrading from a previous version of the BASIC
Stamp Editor and you have set your own default directories, they will not
be replaced with the new source code example directories. Upon opening
the editor, only default directory options that are blank will be redirected
to the source code examples.
FAVORITE DIRECTORIES.
The Favorite Directories list allows you to add and delete folder locations
that will appear as additional options in the File → Open From... and File
→ Save To... menus as well as the Recent list in the integrated explorer. It
works in a similar way as the Module Directories list; however, you can
set your own descriptive names for those folders.
DEBUG APPEARANCE PREFERENCES.
Under the Debug Appearance tab (Figure 3.24) you can set the color and
size of the various Debug Terminal elements; settings apply to all the
Debug Terminal windows at once. A Debug Terminal itself can be resized
and/or moved by simply clicking and dragging the window; each
window’s size and position is remembered even after closing the editor.
THE CHOOSE... BUTTONS.
The Choose… buttons allow you to change the background and font color
of both the Transmitter and Receiver panes, independently. The font size
of both panes can be changed to one of 8 sizes: 6, 8, 10, 12, 14, 18, 24, and
36. The Debug Terminal font size is independent of the font size in the
main editor window.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 63
Using the BASIC Stamp Editor
Figure 3.24: The Debug
Appearance Tab under
Edit → Preferences.
The “Wrap Text to” field gives two options, Pane and Page. Wrapping to
Pane is the default, and causes text to wrap at the right edge of the
Receiver pane, reflecting the current visible size that the user happens to
have set for the Debug Terminal’s window. Wrapping to Page, however,
causes text to wrap at a specific line width, regardless of the user’s current
Debug Terminal window size. The “Page width (characters)” field is
enabled when wrap mode is set to Page. The default page width is 32,
characters and the range is 32 to 128. Note: wrapping to page can be
handy to maintain formatting of formatted tabular information, but could
lead to information being displayed off the edge of the Receive pane if the
Debug Terminal is sized too small.
TEXT WRAPPING IN THE DEBUG
TERMINAL.
The maximum Receive pane buffer size is defined in terms of lines. It can
be set to any power of two between 256 and 8192; 1024 is the default. Data
received by the Debug Terminal is maintained in this buffer for display on
MAXIMUM BUFFER SIZE.
Page 64 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
the screen. If the default is used, for example, you could receive 1024 lines
worth of text from a BASIC Stamp, and still be able to scroll back and view
the first line that was received. Upon receiving the 1025th line of text, the
first line of text is pushed out of the buffer and is lost for good, making the
first visible line in the Receive pane actually be the 2nd line of text that was
received. Larger buffer sizes consume more PC memory (256 * buffer_size
* Number_of_Open_Debug_Terminals bytes), so it is best to set it only as
high as you need it for your application.
The Tab size can be adjusted as well, anywhere from 3 to 16 character
spaces. The default is 8. Keep in mind that most people don’t change this
value, so writing code that relies on a particular setting other than 8 may
display improperly on other user’s Debug Terminals.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 65
Using the BASIC Stamp Editor
Under the Debug Function tab (Figure 3.25), checkboxes allow enabling or
disabling of special processing for 16 different control characters. The
default is for all 16 control characters to be processed, but you may disable
one or more of them if you are using the Debug Terminal to view data
coming from a device other than a BASIC Stamp.
DEBUG FUNCTION PREFERENCES.
Figure 3.25: The Debug Function
Tab under Edit → Preferences.
For example, a device that sends out a 0 to indicate something other than
Clear Screen will cause unintentional clearing of the Receive pane;
unchecking the checkbox for “(0) = Clear Screen” will prevent this from
happening.
Page 66 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
DEBUG PORT PREFERENCES.
Under the Debug Port tab (Figure 3.26), each of the four (4) Debug
Terminal’s default COM port settings may be configured separately.
These settings are only used when the Debug Terminal is manually
opened.
Figure 3.26: The Debug Port Tab
under Edit → Preferences.
You may assign a specific COM port from the available drop-down list;
this list can be changed by clicking on the (...) button to the right. Note
that any Debug Terminals that are opened automatically after a PBASIC
program is downloaded will always default to the COM port and settings
used during download. If NONE is selected as the COM port, the
manually opened Debug Terminal will not open any port upon startup, so
you will have to manually select the desired COM port from the Debug
Terminal window each and every time you open that Debug Terminal.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 67
Using the BASIC Stamp Editor
Advanced Compilation Techniques
For BS2e, BS2sx, BS2p, BS2pe and BS2px modules, each editor page can be
a separate project, or part of a single project. A project is a set of up to
eight files that should all be downloaded to the BASIC Stamp for a single
application. Each of the files within the project is downloaded into a
separate "program slot". Only the BASIC Stamp 2e, 2sx, 2p, 2pe, and 2px
modules support multi-file projects.
INTRODUCTION TO BASIC STAMP
PROJECTS.
For BASIC Stamp projects (consisting of multiple programs), the $STAMP
directive has an option to specify additional filenames. The syntax below
demonstrates this form of the $STAMP directive:
USING THE $STAMP DIRECTIVE TO
DEFINE MULTI-FILE PROJECTS.
'
{ $STAMP
BS2e, file2, file3, …, file8 }
Use this form of the $STAMP directive if a project, consisting of multiple
files, is desired. This form of the directive must be entered only into the
first program (to be downloaded into program slot 0). The file2, file3, etc.
items should be the actual name (and optionally the path) of the other files
in the project. File2 refers to the program that should be downloaded into
program slot 1, file3 is the program that should be downloaded into
program slot 2, etc. If no path is given, the filename is given the path of
program 0 when loading them into the editor.
Up to seven filenames can be included, bringing the total to eight files in
the project all together. Upon loading, tokenizing, running or viewing
program 0 in the Memory Map, the editor will read the $STAMP directive,
determine if the indicated files exist, will load them if necessary and
change their captions to indicate the project they belong to and their
associated program number. After the directive is tokenized properly,
and all associated files are labeled properly, tokenizing, running or
viewing any program in the Memory Map will result in that program’s
entire project being tokenized, downloaded or viewed.
When program #0 of a multi-file project is opened from diskette, the entire
project will be loaded (all referenced files) as well. When a file that is part
of a multi-file project is closed, the entire project (all the associated files)
will be closed as well.
Page 68 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
EASY STEPS TO CREATING MULTI-FILE
PROJECTS.
To create a project consisting of multiple files, follow these steps:
1.
2.
Create the first file in the editor and save it (we'll call it
Sample.bsx). This will be the program that is downloaded into
program slot 0.
Create at least one other file in the editor and save it also (we'll call
it NextProgram.bsx).
Note: At this point the editor tabs will be:
0:Sample.bsx
and
0:NextProgram.bsx.
indicating that there are two unrelated files open "Sample.bsx" and
"NextProgram.bsx" and each will be downloaded into program slot 0.
3.
Go back to the first program and enter or modify the $STAMP
directive using the project format. Use "NextProgram" as the File2
argument. For example:
' {$STAMP
4.
BS2sx,
NextProgram.bsx}
Then tokenize the code by pressing F7 or selecting Run → Check
Syntax from the menu.
At this point, the BASIC Stamp Editor will see the $STAMP directive
and realize that this file (Sample.bsx) is the first file in a project and
that the second file should be NextProgram.bsx. It will then search for
the file on the hard drive (to verify its path is correct), will see that it is
already loaded, and then will change the editor tabs to indicate the
project relationship. At this point the editor tabs will be:
0:Sample.bsx
and
[Sample] 1:NextProgram.bsx.
indicating that there are two related files open; "Sample.bsx" and
"NextProgram.bsx". NextProgram.bsx belongs to the "Sample" project
and it will be downloaded into program slot 1 and Sample.bsx will be
downloaded into program slot 0.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 69
Using the BASIC Stamp Editor
The editor has the ability to treat projects as one logical unit and can
download each of the associated source code files at once. In order to
minimize download time for large projects a Project Download Mode is
available in the Preferences window. The available modes are: “Modified”
(the default), “All” or “Current” and are explained below. This item only
affects download operations for the BS2e, BS2sx, BS2p and BS2pe. See
Table 3.7.
Download Mode
Modified (default)
All
Current
Function
This mode will cause only the source code files that were
modified since the last download to be downloaded next time.
If no files have been modified since the last download, or the
entire project has just been loaded into the editor, all the files
will be downloaded next time. This mode decreases the delay
during downloading projects and should help speed
development and testing.
This mode will cause all the source code files to be
downloaded each time. This will be noticeably slow with large
projects.
This mode will cause only the current source code file to be
downloaded, ignoring all the others. This mode can be helpful,
but can lead to development errors if you forget to download a
required program.
PROJECT DOWNLOAD MODES.
Table 3.7: Project Download
Modes.
Regardless of the download mode selected, the programs will be
downloaded into the program slot indicated in their tab.
Some source code may be suitable for multiple uses but requires changing
a set of constants as needed for each case. For example, you may want to
run the same program on a BS2 and a BS2sx, but the resolution of timesensitive commands is different, requiring slight code modifications.
Several conditional compile directives exist in PBASIC 2.5 to assist with
this situation. Table 3.8 lists the available directives.
Directive
#DEFINE
#IF...#THEN...#ELSE
#SELECT...#CASE
#ERROR
Function
Allows the programmer to create custom symbols for use
within conditional compilation control structures.
Evaluate Condition and, if it is True, compile the statement(s)
following #THEN, otherwise compile the statements following
#ELSE.
Evaluate Expression and then conditionally compile a block of
code based on comparison to Condition(s). If no conditions are
found True and a #CASE ELSE block is included, the #CASE
#ELSE code statements will compiled.
Allows the programmer to create a custom error dialog.
Page 70 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
CONDITIONAL COMPILE DIRECTIVES.
Table 3.8: Conditional Compile
Directives.
NOTE: These directives require
PBASIC 2.5.
3: Using the BASIC Stamp Editor
Lets look at the syntax and examples for each conditional compile
directive. For an explanation of syntax conventions, see page 128.
#DEFINE SYNTAX.
#DEFINE Symbol { = Value }
#DEFINE allows the programmer to create custom, compile-time, symbols
for use within conditional compile control structures.
• Symbol is a unique symbol name that will optionally represent
a Value.
• Value is an optional constant/expression specifying the value
of Symbol. If the value parameter is omitted, Symbol is defined
as true (-1).
Example:
' {$PBASIC 2.5}
#DEFINE DebugMode
#IF DebugMode #THEN DEBUG "Debugging."
STOP
In the example above, the #DEFINE statement defines DebugMode to be
“true” (-1), since there is no Value argument provided. The second line is
another conditional compile statement, #IF…#THEN (see below for more
information) which evaluates the state of DebugMode, determines it is true
and then allows the following DEBUG statement to be compiled into the
program. The last line, STOP, is compiled into the program afterwards.
The result of compiling this example is a program with only two
executable statements, DEBUG "Debugging", CR and STOP. The real
power of this example, however, is more obvious when you comment out,
or remove, the #DEFINE line. Look at the next example, below:
' {$PBASIC 2.5}
' #DEFINE DebugMode
#IF DebugMode #THEN DEBUG "Dubugging."
STOP
Here we commented out the #DEFINE line, effectively removing that line
from the program. This means that the symbol DebugMode will be
undefined, and undefined conditional compile symbols are treated as
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 71
Using the BASIC Stamp Editor
False (0). Upon compiling this example, the #IF…#THEN statement will
evaluate DebugMode, which is False (because it is undefined) and then will
not allow the DEBUG statement to be compiled.
Only the STOP
command will be compiled into the program in this example. This is a
very powerful feature for quickly removing many DEBUG statements (or
other statements) from a program when you’re done developing it, but
leaving the possibility of re-enabling all those statements should further
maintenance be required at a later time.
The optional Value argument can be used, for example, to select modes of
operation:
' {$PBASIC 2.5}
#DEFINE SystemMode = 2
#IF SystemMode = 1 #THEN
HIGH 1
#ELSE
LOW 1
#ENDIF
In the example above, the first line defines SystemMode to be equal to 2.
The #IF…#THEN statement evaluates the state of SystemMode, determines
it is 2, so the condition is false, and then it skips the statement after #THEN
and allows the statement following #ELSE to be compiled into the
program.
Note, conditional compile directives are evaluated just before the program
is compiled, so variables and named constants cannot be referenced within
a conditional compile definition. Compile-time symbols created with
#DEFINE can, however, be referenced by conditional compile commands.
#IF Condition(s) #THEN
Statement(s)
{ #ELSE
Statement(s) }
#ENDIF
Page 72 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
#IF...#THEN SYNTAX.
3: Using the BASIC Stamp Editor
#IF…#THEN is a conditional compile structure similar to the run-time
IF…THEN command except that, at compile time, #IF…#THEN evaluates
Condition(s) and, if it is True, compiles the Statement(s) following #THEN,
otherwise it compiles the Statement(s) following #ELSE.
• Condition is a statement that can be evaluated as True or False
during compile-time.
• Statement is any valid PBASIC instruction.
Example:
' {$PBASIC 2.5}
' set Baud for 9600-N81
#IF ($STAMP = BS2sx) OR ($STAMP = BS2p) #THEN
Baud CON 16624
#ELSE
#IF ($STAMP = BS2px)
Baud CON 16780
#ELSE
Baud CON 16468
#ENDIF
#ENDIF
In this example, the constant Baud is set to an appropriate value for the
BASIC Stamp that is specified in the $STAMP directive (not shown). This
code will work with the BS2, BS2e, BS2sx, BS2p, BS2pe, and BS2px.
One important thing to note is that the $STAMP directive is used here as a
compile-time symbol, as if it were defined by #DEFINE. The compiler
treats all the editor directives, $STAMP, $PBASIC and $PORT as “defined”
compile-time symbols set equal to the respective value used in their
declaration. At the time of this writing, using $PBASIC in this fashion is
pointless since the conditional-compile directives are only supported in
PBASIC 2.5, and would cause an error if compiled in any other version of
the language.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 73
Using the BASIC Stamp Editor
#SELECT...#CASE SYNTAX.
#SELECT Expression
#CASE Condition(s)
Statement(s)
{ #CASE Condition(s)
Statement(s)
#CASE #ELSE
Statement(s) }
#ENDSELECT
#SELECT…#CASE is a conditional compile structure similar to the runtime SELECT…CASE command except that, at compile time,
#SELECT…#CASE evaluates Expression and then conditionally compiles a
block of code based on comparison to Condition(s). If no Conditions are
found to be True and a #CASE #ELSE block is included, the Statement(s) in
the #CASE #ELSE block will be compiled.
• Expression is a statement that can be evaluated as True or False
during compile-time.
• Condition is a statement, that when compared to Expression,
can be evaluated as True or False. Multiple conditions within
the same CASE can be separated by commas ( , ).
• Statement is any valid PBASIC instruction.
Example:
' {$PBASIC 2.5}
#SELECT $STAMP
#CASE BS2, BS2e, BS2sx
GOSUB LCD_Write
#CASE #ELSE
LCDOUT LCDpin, cmd, [char]
#ENDSELECT
This example checks the $STAMP directive at compile-time and either
compiles
GOSUB LCD_Write
- or –
LCDOUT LCDpin, cmd, [char] into
the program.
Page 74 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
#ERROR SYNTAX.
#ERROR Message
#ERROR displays a compile-time error. This allows the programmer to
flag fatal errors during compilation.
• Message is the error message string, enclosed in quotes.
Example:
' {$PBASIC 2.5}
#DEFINE I2CReady = (($STAMP = BS2p) OR ($STAMP = BS2pe) OR ($STAMP = BS2px))
#IF NOT I2CReady #THEN
#ERROR "BS2p, BS2pe, or BS2px is required for this program."
#ENDIF
When compiled, this example will cause the editor to halt compilation and
display the dialog below if you attempt to compile for a BASIC Stamp
model other than the BS2p, BS2pe, or BS2px:
Figure 3.27: Custom Error
Message using the #ERROR
directive.
Features for Developers
The BASIC Stamp Editor has several features that are designed to support
the needs of developers. Note: when installing the BASIC Stamp editor,
you can instruct the installer to include additional developer resources by
selecting the “Custom” option from the “Setup Type” prompt.
GENERATE OBJECT CODE FEATURE.
The Generate Object Code feature allows you to tokenize a PBASIC
program and save it to a file in the tokenized form. This allows you to
send your BASIC Stamp object code (the actual binary data that is
downloaded to the BASIC Stamp module) to other people without having
to reveal your PBASIC source code. If you are a developer who has
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 75
Using the BASIC Stamp Editor
customers using BASIC Stamp-based products, you can release firmware
updates to them in this manner.
Object code can be saved as a separate .obj file (downloadable with the
StampLoader.exe program) or as a single executable (integrated with the
StampLoader.exe inside of it). The single executable method provides a
simpler way to pass your firmware update on to your customers.
Any syntactically correct PBASIC source code can be used with the
Generate Object Code feature; this includes BS1 and BS2 code as well as
BS2e, BS2sx, BS2p, BS2pe, and BS2px code that is either a single file or a
multi-file project. Note: The original DOS-based software for the BS1
included a directive called BSAVE; when used it would cause the software
to generate an object file. In the BASIC Stamp Windows Editor, the
Generate Object Code feature replaces and enhances the BSAVE feature;
the reserved word BSAVE is still accepted in BS1 source code, but is
simply ignored. Old BS1 object code saved via the BSAVE option is not
compatible with the StampLoader.exe program so you must regenerate
the object file using the BASIC Stamp Windows Editor.
If you don’t have the StampLoader.exe program, it can be automatically
generated for you by selecting the second output file option, “Object Code
and Stamp Loader”, in the Generate Object Code window. Additionally,
firmware, product, company and related info can be embedded in the
object code or single executable file for your customers to view before
downloading.
Page 76 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
3: Using the BASIC Stamp Editor
Figure 3.28: The Generate Object
Code Window.
In the example above, we chose to generate a single executable with
custom names and messages as shown. Then we clicked the Generate…
button (which prompted us for a file name) and the file was created.
When a user runs the file we just generated, they see a screen similar to the
figure below:
Figure 3.29: Example customized
StampLoader.exe file.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 77
Using the BASIC Stamp Editor
Another feature of interest to some developers is the BASIC Stamp
Editor’s Command Line interface. This interface provides for command
line, batch file or third-party driven control of the editor.
The Stampw.exe program is a Win32 application that can be run through
any standard method. When run with the command-line options,
however, it provides special features that developers and product
manufacturing managers may find useful. While this program can be run
from a command prompt on a Windows system, it will not work on a
DOS-only system.
The Stampw.exe supports redirection of its input and output via the
standard pipe mechanisms. If its output is redirected via the commandline (ex: Stampw.exe myfile.bs2 > Test1.txt) the designated output file,
Test1.txt in this case, will be created and various information about the
processing of the source file will be stored there. This information directly
reflects the information available on the GUI prompts, interactions with
the user and downloading status. This feature can be combined with the
/NoDebug and /NoPrompts switches for various levels of GUI interaction
with the user; including completely hidden operation.
The following is the syntax of the BASIC Stamp Editor’s command-line
switches.
Stampw.exe {/Com#} {{/ReadOnly}
source_file}
Stampw.exe {/Com#} /Download {/Updates}{/NoDebug}{/NoPrompts} source_file > output_file
Stampw.exe {/Com#} /Identify {/NoPrompts} > output_file
Stampw.exe /Tokenize source_file > output_file
Stampw.exe /Pipe master_file
Stampw.exe /Help
Table 3.9 gives a function description for each command-line switch.
Page 78 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
COMMAND LINE INTERFACE.
3: Using the BASIC Stamp Editor
Table 3.9: Command Line
Switches
Command
/Com#
/ReadOnly
/Identify
/Tokenize
/Download
/Updates
/NoDebug
/NoPrompts
/Pipe
master_file
/Help
Function
Specify com port (serial port) to download to. # is a valid com port
number. NOTE: must be one word, i.e.: Com2 indicates com port 2.
Open source_file in read-only mode. The Ctrl key acts as a download key
when in read-only mode. Requires source_file argument. This command
option is not available if double-piped communication is established.
Identify BASIC Stamp modules on COM ports. Requires redirection to
output_file.
Tokenize source code.
No prompts will be displayed.
Requires
source_file argument and redirection to output_file.
Tokenize source code, and download it (if tokenization successful).
Requires source_file argument and redirection to output_file.
Provides program slot number (if applicable) and download-percentagecomplete status updates during download.
No Debug Terminal opens after downloading (even if code contains
DEBUGs) and COM port is immediately closed after downloading. This
option requires /Download switch. Note: This switch will have no effect if
Debug Terminal is already open from a previous operation.
No screen prompts at all (except for Debug Terminal). This option requires
/Download switch.
Start up master_file (must be .exe) and establish bi-directional
communication pipes (double-piped communication) for master-programcontrolled execution. Stampw.exe remains open until master_file breaks
pipe.
This command option is not available once double-piped
communication is established.
Display command-line help. This command option is not available if doublepiped communication is established.
When the output of the BASIC Stamp Editor is piped to a file or a master
program, it displays all of its messages in a specific, predefined format.
Each message has a unique 3-digit number. Detailed information about
the use of command-line options, including a table of all messages with
their ID numbers, can be found in the “What’s New in Stamp.exe”
document included with the typical installation of the Stamp Editor.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 79
Using the BASIC Stamp Editor
Page 80 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
4: BASIC Stamp Architecture – Memory Organization
BASIC Stamp Architecture Introduction This chapter provides detail on
the architecture (RAM usage) and math functions of the BS1, BS2, BS2e,
BS2sx, BS2p, BS2pe, and BS2px.
The following icons will appear to indicate where there are differences
among the various BASIC Stamp models:
One or more of these icons indicates the item applies only
to the BS1, BS2, BS2e, BS2sx, BS2p, BS2pe, or BS2px
respectively.
All
2 If an item applies to the all of the models in the BS2
family, this icon is used.
The BASIC Stamp has two kinds of memory; RAM (for variables used by
your program) and EEPROM (for storing the program itself). EEPROM
may also be used to store long-term data in much the same way that
desktop computers use a hard drive to hold both programs and files.
MEMORY ORGANIZATION
An important distinction between RAM and EEPROM is this:
•
•
RAM ORGANIZATION (BS1)
THE INPUT/OUTPUT VARIABLES.
1
RAM loses its contents when the BASIC Stamp loses power; when
power returns, all RAM locations are cleared to 0s.
EEPROM retains the contents of memory, with or without power,
until it is overwritten (such as during the program-downloading
process or with a WRITE instruction.)
The BS1 has 16 bytes (8 words) of RAM space arranged as shown in Table
4.1 The first word, called PORT, is used for I/O pin control. It consists of
two bytes, PINS and DIRS. The bits within PINS correspond to each of the
eight I/O pins on the BS1. Reading PINS effectively reads the I/O pins
directly, returning an 8-bit set of 1's and 0's corresponding to the high and
low state of the respective I/O pin at that moment. Writing to PINS will
store a high or low value on the respective I/O pins (though only on pins
that are set to outputs).
The second byte of PORT, DIRS, controls the direction of the I/O pins.
Each bit within DIRS corresponds to an I/O pin's direction. A high bit (1)
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 81
BASIC Stamp Architecture – Memory Organization
sets the corresponding I/O pin to an output direction and a low bit (0) sets
the corresponding I/O pin to an input direction.
The remaining words (W0 – W6) are available for general-purpose use.
Each word consists of separately addressable bytes and the first two bytes
(B0 and B1) are bit addressable as well.
You may assign other names (symbols) to these RAM registers as shown
in section "Defining and Using Variables", below.
When the BS1 is powered up, or reset, all memory locations are cleared to
0, so all pins are inputs (DIRS = %00000000). Also, if the PBASIC program
sets all the I/O pins to outputs (DIRS = %11111111), then they will initially
output low, since the output latch (PINS) is cleared to all zeros upon
power-up or reset, as well.
Word Name
PORT
W0
W1
W2
W3
W4
W5
W6
Byte Names
PINS
DIRS
B0
B1
B2
B3
B4
B5
B6
B7
B8
B9
B10
B11
B12
B13
Bit Names
PIN0 – PIN7
DIR0 – DIR7
BIT0 – BIT7
BIT8 – BIT15
Special Notes
I/O pins; bit addressable.
I/O pins directions; bit addressable.
Bit addressable.
Bit addressable.
Table 4.1: BS1 RAM Organization.
Note: There are eight words,
consisting of two bytes each for a
total of 16 bytes. The bits within
the upper two words are
individually addressable.
Used by GOSUB instruction.
Used by GOSUB instruction.
The BS2, BS2e, and BS2sx models have 32 bytes of Variable RAM space
arranged as shown in Table 4.2. Of these, the first six bytes are reserved
for input, output, and direction control of the I/O pins. The remaining 26
bytes are available for general-purpose use as variables.
The BS2p, BS2pe, and BS2px models have an extra set of INS, OUTS, and
DIRS registers for a total of 38 bytes of variable RAM. These are “shadow”
registers that are switched in and out of the memory map with the
AUXIO, MAINIO, and IOTERM commands. While this feature exists in
Page 82 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
RAM ORGANIZATION.
4: BASIC Stamp Architecture – Memory Organization
the variable RAM for these models, only the BS2p40 module has the extra
16 I/O pins for which this feature is intended.
THE INPUT/OUTPUT VARIABLES.
The word variable INS is unique in that it is read-only. The 16 bits of INS
reflect the state of I/O pins P0 through P15. It may only be read, not
written. OUTS contains the states of the 16 output latches. DIRS controls
the direction (input or output) of each of the 16 I/O pins.
A 0 in a particular DIRS bit makes the corresponding pin an input and a 1
makes the corresponding pin an output. So if bit 5 of DIRS is 0 and bit 6 of
DIRS is 1, then I/O pin 5 (P5) is an input and I/O pin 6 (P6) is an output.
A pin that is an input is at the mercy of circuitry outside the BASIC Stamp;
the BASIC Stamp cannot change its state. A pin that is an output is set to
the state indicated by the corresponding bit of the OUTS register.
When the BASIC Stamp is powered up, or reset, all memory locations are
cleared to 0, so all pins are inputs (DIRS = %0000000000000000). Also, if
the PBASIC program sets all the I/O pins to outputs (DIRS =
%1111111111111111), then they will initially output low, since the output
latch (OUTS) is cleared to all zeros upon power-up or reset, as well.
Table 4.2: RAM Organization for
all BS2 models.
NOTE: There are 16 words, of
two bytes each for a total of 32
bytes*. All bits are individually
addressable through variable
modifiers; the bits within the
upper three words are also
individually addressable though
the pre-defined names shown.
All registers are word, byte,
nibble and bit addressable.
*The BS2p, BS2pe, and BS2px
have an additional set of INS,
OUTS, and DIRS registers that
are switched in and out of the
memory map in place of the main
INS, OUTS, and DIRS registers
by using AUXIO, MAINIO, and
IOTERM. Only the BS2p40 has
the required extra I/O pins this
feature is intended for.
Word Name
INS*
OUTS*
DIRS*
W0
W1
W2
W3
W4
W5
W6
W7
W8
W9
W10
W11
W12
Byte Names
INL, INH
OUTL, OUTH
DIRL, DIRH
Nibble Names
INA, INB
INC, IND
OUTA, OUTB
OUTC, OUTD
DIRA, DIRB
DIRC, DIRD
Bit Names
IN0 – IN7
IN8 – IN15
OUT0 – OUT7
OUT8 – OUT15
DIR0 – DIR7
DIR8 – DIR15
Special Notes
Input pins
Output pins
I/O pin direction control
B0, B1
B2, B3
B4, B5
B6, B7
B8, B9
B10, B11
B12, B13
B14, B15
B16, B17
B18, B19
B20, B21
B22, B23
B24, B25
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 83
BASIC Stamp Architecture – Memory Organization
The INS variable always shows the state of the I/O pins themselves,
regardless of the direction of each I/O pin. We call this, "reading the
pins". If a pin was set to an input mode (within DIRS) and an external
circuit connected the I/O pin to ground, the corresponding bit of INS
would be low. If a pin was set to an output mode and the pin's state was
set to a high level (within OUTS), the corresponding bit of INS would be
high. If, however, that same pin was externally connected directly to
ground, the corresponding bit of INS would be low; since we're reading
the state of the pin itself and the BASIC Stamp cannot override a pin that is
driven to ground or 5 volts externally. Note: The last example is an error,
is a direct short and can cause damage to the BASIC Stamp! Do not
intentionally connect output pins directly to an external power source or
you risk destroying your BASIC Stamp.
To summarize: DIRS determines whether a pin’s state is set by external
circuitry (input, 0) or by the state of OUTS (output, 1). INS always matches
the actual states of the I/O pins, whether they are inputs or outputs. OUTS
holds bits that will only appear on pins whose DIRS bits are set to output.
SUMMARY OF THE FUNCTION OF DIRS,
INS AND OUTS.
In programming the BASIC Stamp, it’s often more convenient to deal with
individual bytes, nibbles or bits of INS, OUTS and DIRS rather than the
entire 16-bit words. PBASIC has built-in names for these elements, shown
in Table 4.2.
Here's an example of what is described in Table 4.2. The INS register is 16bits (corresponding to I/O pins 0 though 15). The INS register consists of
two bytes, called INL (the Low byte) and INH (the High byte). INL
corresponds to I/O pins 0 through 7 and INH corresponds to I/O pins 8
though 15. INS can also be thought of as containing four nibbles, INA,
INB, INC and IND. INA is I/O pins 0 though 3, INB is I/O pins 4 though
7, etc. In addition, each of the bits of INS can be accessed directly using
the names IN0, IN1, IN2… IN5.
The same naming scheme holds true for the OUTS and DIRS variables as
well.
As Table 4.2 shows, the BASIC Stamp module’s memory is organized into
16 words of 16 bits each. The first three words are used for I/O. The
remaining 13 words are available for use as general-purpose variables.
Page 84 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
PREDEFINED "FIXED" VARIABLES.
4: BASIC Stamp Architecture – Defining Variables
2
The 40-pin BS2p uses the first three words for I/O even though it has
twice as many I/O pins. This is done with the AUXIO, MAINIO, and
IOTERM commands, which effectively switch the auxiliary I/O registers
in and out of the INS, OUTS, and DIRS locations.
Just like the I/O variables, the general-purpose variables have predefined
names: W0 through W12 and B0 through B25. B0 is the low byte of W0; B1
is the high byte of W0; and so on through W12 (B24=low byte, B25=high
byte). Unlike I/O variables, there’s no reason that your program variables
have to be stuck in a specific position in the BASIC Stamp’s physical
memory. A byte is a byte regardless of its location. And if a program uses
a mixture of variables of different sizes, it can be difficult to logically dole
them out or allocate storage.
p
More importantly, mixing fixed variables with automatically allocated
variables (discussed in the next section) is an invitation to bugs. A fixed
variable can overlap an allocated variable, causing data meant for one
variable to show up in another! The fixed variable names (of the generalpurpose variables) are only provided for power users who require
absolute access to a specific location in RAM.
We recommend that you avoid using the fixed variables in most
situations. Instead, let PBASIC allocate variables as described in the next
section. The editor software will organize your storage requirements to
make optimal use of the available memory.
Before you can use a variable in a PBASIC program you must declare it.
All 2 “Declare” means letting the BASIC Stamp know that you plan to use a
variable, what you want to call it, and how big it is. Although PBASIC
does have predefined variables that you can use without declaring them
first (see previous sections), the preferred way to set up variables is to use
the directive SYMBOL (for the BS1) or VAR (for all BS2 models). Here is
the syntax for a variable declaration:
DEFINING AND USING VARIABLES (VAR).
1
1
SYMBOL
name
=
RegisterName
-- or -All
2
name VAR
Size
where name is the name by which you will refer to the variable,
RegisterName is the "fixed" name for the register and size indicates the
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 85
BASIC Stamp Architecture – Defining Variables
number of bits of storage for the variable. NOTE: The top example is for
the BS1 and the bottom example is for all BS2 models.
There are certain rules regarding symbol names. Symbols must start with
a letter or underscore, can contain a mixture of letters, numbers, and
underscore (_) characters, and must not be the same as PBASIC reserved
words, or labels used in your program. Additionally, symbols can be up to
32 characters long. See Appendix B for a list of PBASIC reserved words.
PBASIC does not distinguish between upper and lower case, so the names
MYVARIABLE, myVariable, and MyVaRiAbLe are all equivalent.
THE RULES OF SYMBOL NAMES.
For the BS1, the register name is one of the predefined "fixed" variable
names, such as W0, W1, B0, B1, etc. Here are a few examples of variable
declarations on the BS1:
1
SYMBOL
SYMBOL
SYMBOL
1
temporary = W0
counter
= B1
result
= B2
' value can be 0 to 65535
' value can be 0 to 255
' value can be 0 to 255
The above example will create a variable called temporary whose contents
will be stored in the RAM location called W0. Also, the variable counter
will be located at RAM location B1 and result at location B2. Note that
temporary is a word-sized variable (because that's what size W0 is) while
the other two are both byte-sized variables. Throughout the rest of the
program, we can use the names temporary, counter, and result instead of
W0, B1 and B2, respectively. This makes the code much more readable; it's
easier to determine what counter is used for than it would be to figure out
what the name B1 means. Please note that counter resides at location B1,
and B1 happens to be the high byte of W0. This means than changing
counter will also change temporary since they overlap. A situation like this
usually is a mistake and results in strange behavior, but is also a powerful
feature if used carefully.
For all BS2 models, the Size argument has four choices: 1) Bit (1 bit), 2) Nib
(nibble; 4 bits), 3) Byte (8 bits), and 4) Word (16 bits). Here are some
examples of variable declarations on the BS2 models:
All
2
mouse
cat
dog
rhino
All
2
VAR
VAR
VAR
VAR
BIT
NIB
BYTE
WORD
'
'
'
'
Value
Value
Value
Value
can
can
can
can
be
be
be
be
0
0
0
0
or
to
to
to
1.
15.
255.
65535.
Page 86 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
4: BASIC Stamp Architecture – Defining Arrays
The above example will create a bit-sized variable called mouse, and
nibble-sized variable called cat, a byte-sized variable called dog and a
word-sized variable called rhino. Unlike in the BS1, these variable
declarations don't point to a specific location in RAM. Instead, we only
specified the desired size for each variable; the BASIC Stamp will arrange
them in RAM as it sees fit. Throughout the rest of the program, we can
use the names mouse, cat, dog and rhino to set or retrieve the contents of
these variables.
A variable should be given the smallest size that will hold the largest
value that will ever be stored in it. If you need a variable to hold the
on/off status (1 or 0) of switch, use a bit. If you need a counter for a
FOR…NEXT loop that will count from 1 to 100, use a byte. And so on.
If you assign a value to a variable that exceeds its size, the excess bits will
be lost. For example, suppose you use the byte variable dog, from the
example above, and write dog = 260 (%100000100 binary). What will dog
contain? It will hold only the lowest 8 bits of 260: %00000100 (4 decimal).
DEFINING ARRAYS.
All
2
On all BS2 models, you can also define multipart variables called arrays.
An array is a group of variables of the same size, and sharing a single
name, but broken up into numbered cells, called elements. You can define
an array using the following syntax:
name
VAR
Size(n)
where name and Size are the same as described earlier. The new argument,
(n), tells PBASIC how many elements you want the array to have. For
example:
myList
VAR
Byte(10)
' Create a 10-byte array.
Once an array is defined, you can access its elements by number.
Numbering starts at 0 and ends at n-1. For example:
myList(3) = 57
DEBUG ? myList(3)
This code will display "myList(3) = 57" on the PC screen. The real power of
arrays is that the index value can be a variable itself. For example:
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 87
BASIC Stamp Architecture – Defining Arrays
myBytes
idx
VAR
VAR
Byte(10)
Nib
' Define 10-byte array
' Define 4-bit var
FOR idx = 0 TO 9
myBytes(idx) = idx * 13
NEXT
' Repeat with idx = 0, 1, 2...9
' Write idx * 13 to each cell
FOR idx = 0 TO 9
DEBUG ? myBytes(idx)
NEXT
STOP
' Repeat with idx = 0, 1, 2...9
' Show contents of each cell
If you run this program, DEBUG will display each of the 10 values stored
in the elements of the array: myBytes(0) = 0*13 = 0, myBytes(1) = 1*13 = 13,
myBytes(2) = 2*13 = 26 ... myBytes(9) = 9*13 = 117.
A word of caution about arrays: If you’re familiar with other BASICs and
have used their arrays, you have probably run into the “subscript out of
range” error. Subscript is another term for the index value. It is
out-of-range when it exceeds the maximum value for the size of the array.
For instance, in the example above, myBytes is a 10-cell array. Allowable
index numbers are 0 through 9. If your program exceeds this range,
PBASIC will not respond with an error message. Instead, it will access the
next RAM location past the end of the array. If you are not careful about
this, it can cause all sorts of bugs.
If accessing an out-of-range location is bad, why does PBASIC allow it?
Unlike a desktop computer, the BASIC Stamp doesn’t always have a
display device connected to it for displaying error messages. So it just
continues the best way it knows how. It’s up to the programmer (you!) to
prevent bugs. Clever programmers, can take advantage of this feature,
however, to perform tricky effects.
Another unique property of PBASIC arrays is this: You can refer to the 0th
cell of the array by using just the array’s name without an index value. For
example:
myBytes
VAR
myBytes(0) = 17
DEBUG ? myBytes(0)
DEBUG ? myBytes
Byte(10)
' Define 10-byte array
' Store 17 to 0th cell
' Display contents of 0th cell
' Also displays 0th cell
Page 88 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
All
2
4: BASIC Stamp Architecture – Aliases and Modifiers
This feature is how the "string" capabilities of the DEBUG and SEROUT
command expect to work. A string is simply a byte array used to store
text. See "Displaying Strings (Byte Arrays)" in the DEBUG command
description on page 166 for more information.
An alias is an alternative name for an existing variable. For example:
ALIASES AND VARIABLE MODIFIERS.
1
SYMBOL
SYMBOL
cat
tabby
= B0
= cat
' Create a byte-sized variable
' Create alias for cat
Byte
cat
' Create a byte-sized variable
' Create alias for cat
-- or -All
2
cat
tabby
VAR
VAR
In this example, tabby is an alias to the variable cat. Anything stored in cat
shows up in tabby and vice versa. Both names refer to the same physical
piece of RAM. This kind of alias can be useful when you want to reuse a
temporary variable in different places in your program, but also want the
variable’s name to reflect its function in each place. Use caution, because it
is easy to forget about the aliases; during debugging, you might end up
asking ‘How did that value get here?!’ The answer is that it was stored in
the variable’s alias.
All
2
On all the BS2 models, an alias can also serve as a window into a portion
of another variable. This is done using "modifiers." Here the alias is
assigned with a modifier that specifies what part to reference:
rhino
head
tail
VAR
VAR
VAR
Word
rhino.HIGHBYTE
rhino.LOWBYTE
' A 16-bit variable
' Highest 8 bits of rhino
' Lowest 8 bits of rhino
Given that example, if you write the value %1011000011111101 to rhino,
then head would contain %10110000 and tail would contain %11111101.
Table 4.3 lists all the variable modifiers. PBASIC 2.0 and 2.5 lets you apply
these modifiers to any variable name and to combine them in any fashion
that makes sense. For example, it will allow:
rhino
eye
VAR
VAR
Word
' A 16-bit variable
rhino.HIGHBYTE.LOWNIB.BIT1 ' A bit
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 89
BASIC Stamp Architecture – Aliases and Modifiers
Symbol
LOWBYTE
HIGHBYTE
BYTE0
BYTE1
LOWNIB
HIGHNIB
NIB0
NIB1
NIB2
NIB3
LOWBIT
HIGHBIT
BIT0
BIT1
BIT2
BIT3
BIT4 … BIT7
BIT8 … Bit15
Definition
low byte of a word
high byte of a word
byte 0 (low byte) of a word
byte 1 (high byte) of a word
low nibble of a word or byte
high nibble of a word or byte
nib 0 of a word or byte
nib 1 of a word or byte
nib 2 of a word
nib 3 of a word
low bit of a word, byte, or nibble
high bit of a word, byte, or nibble
bit 0 of a word, byte, or nibble
bit 1 of a word, byte, or nibble
bit 2 of a word, byte, or nibble
bit 3 of a word, byte, or nibble
bits 4 though 7 of a word or byte
bits 8 through 15 of a word
The common sense rule for combining modifiers is that they must get
progressively smaller from left to right. It would make no sense to specify,
for instance, the low byte of a nibble, because a nibble is smaller than a
byte! And just because you can stack up modifiers doesn’t mean that you
should unless it is the clearest way to express the location of the part you
want get at. The example above might be improved:
rhino
eye
VAR
VAR
Word
rhino.BIT9
' A 16-bit variable
' A bit
Although we’ve only discussed variable modifiers in terms of creating
alias variables, you can also use them within program instructions:
rhino
head
VAR
VAR
Word
rhino.HIGHBYTE
rhino = 13567
DEBUG ? head
DEBUG ? rhino.HIGHBYTE
STOP
' A 16-bit variable
' Highest 8 bits of rhino
' Display alias variable head
' rhino.HIGHBYTE works too
Modifiers also work with arrays. For example:
myBytes
VAR
Byte(10)
myBytes(0) = $AB
DEBUG HEX ? myBytes.LOWNIB(0)
DEBUG HEX ? myBytes.LOWNIB(1)
' Define 10-byte array
' Hex $AB into 0th byte
' Show low nib ($B)
' Show high nib ($A)
Page 90 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 4.3: Variable Modifiers for all
BS2 models.
All
2
4: BASIC Stamp Architecture – Aliases and Modifiers
If you looked closely at that example, you probably thought it was a
misprint. Shouldn’t myBytes.LOWNIB(1) give you the low nibble of byte 1
of the array rather than the high nibble of byte 0? Well, it doesn’t. The
modifier changes the meaning of the index value to match its own size. In
the example above, when myBytes() is addressed as a byte array, it has 10
byte-sized cells numbered 0 through 9. When it is addressed as a nibble
array, using myBytes.LOWNIB(), it has 20 nibble-sized cells numbered 0
through 19. You could also address it as individual bits using
myBytes.LOWBIT(), in which case it would have 80 bit-sized cells
numbered 0 through 79.
What if you use something other than a “low” modifier, say
myBytes.HIGHNIB()? That will work, but its effect will be to start the
nibble array with the high nibble of myBytes(0). The nibbles you address
with this nib array will all be contiguous, one right after the other, as in the
previous example.
myBytes
VAR
Byte(10)
myBytes(0) = $AB
myBytes(1) = $CD
DEBUG HEX ? myBytes.HIGHNIB(0)
DEBUG HEX ? myBytes.HIGHNIB(1)
' Define 10-byte array.
'
'
'
'
Hex $AB into 0th byte
Hex $CD into next byte
Show high nib of cell 0 ($A)
Show next nib ($D)
This property of modified arrays makes the names a little confusing. If you
prefer, you can use the less-descriptive versions of the modifier names;
BIT0 instead of LOWBIT, NIB0 instead of LOWNIB, and BYTE0 instead of
LOWBYTE. These have exactly the same effect, but may be less likely to be
misconstrued.
You may also use modifiers with the 0th cell of an array by referring to
just the array name without the index value in parentheses. It’s fair game
for aliases and modifiers, both in VAR directives and in instructions.
THE MEMORY MAP
On all BS2 models, if you’re working on a program and wondering how
much variable space you have left, you can use the Memory Map feature
of the editor (CTRL-M). See the "Memory Map" section of Chapter 3 on
page 50.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 91
BASIC Stamp Architecture – Scratch Pad RAM
The BS2e, BS2sx, BS2p, BS2pe, and BS2px have some additional RAM
called Scratch Pad RAM. The BS2e and BS2sx have 64 bytes of Scratch Pad
RAM (0 to 63) and the BS2p, BS2pe, and BS2px have 136 bytes of Scratch
Pad RAM (0-135). Scratch Pad RAM can only be accessed with the GET
and PUT commands and cannot have variable names assigned to it. Table
4.4 shows the layout of all SPRAM registers.
Notice that the highest locations in Scratch Pad RAM (location 63 in the
BS2e and BS2sx, locations 127-135 in the BS2p, BS2pe, and BS2px) are
special-purpose, read-only locations that always contain special run-time
information. For example, the lowest nibble of location 63 (BS2e and
BS2sx) or 127 (BS2p, BS2pe, and BS2px) contains the number of the
currently running program slot. This is handy for programs that need to
know which program slot they exist in. In the BS2p, BS2pe, and BS2px,
the high nibble of location 127 holds the slot designated for READ and
WRITE; see the STORE command on page 449 for more information.
Page 92 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
SCRATCH PAD RAM
4: BASIC Stamp Architecture – Scratch Pad RAM
Table 4.4: Layout of SPRAM
Registers.
NOTE: Scratch Pad RAM can
only be accessed with the GET
and PUT commands. Scratch
Pad RAM cannot have variable
names assigned to it.
Location
0...62
64..126
BS2e and BS2sx
General Purpose RAM
Bits 0-3: Active program
slot number.
n/a
127
n/a
128
n/a
129
n/a
130
n/a
131
n/a
132
n/a
133
n/a
134
n/a
135
n/a
63
BS2p, BS2pe and BS2px
General Purpose RAM
General Purpose RAM
General Purpose RAM
Bits 0-3, Active program slot #. Bits 4-7, program
slot for READ and WRITE operations.
Polled input trigger status of Main I/O pins 0-7
(0 = not triggered, 1 = triggered).
Polled input trigger status of Main I/O pins 8-15
(0 = not triggered, 1 = triggered).
Polled input trigger status of Auxiliary I/O pins
0-7 (0 = not triggered, 1 = triggered).
Polled input trigger status of Auxiliary I/O pins
8-15 (0 = not triggered, 1 = triggered).
Bits 0-3: Polled-interrupt mode, set by
POLLMODE
Bits 0-2: Polled-interrupt “run” slot, set by
POLLRUN.
Bit 0: Active I/O group; 0 =Main I/O,
1 = Auxiliary I/O.
Bit 0: Polled-output status (set by POLLMODE);
0 = disabled, 1= enabled.
Bit 1: Polled-input status; 0 = none defined,
1 = at least one defined.
Bit 2: Polled-run status (set by POLLMODE);
0 = disabled, 1 = enabled.
Bit 3: Polled-output latch status;
0 = real-time mode, 1 = latch mode.
Bit 4: Polled-input state;
0 = no trigger, 1 = triggered.
Bit 5: Polled-output latch state;
0 = nothing latched, 1 = signal latched.
Bit 6: Poll-wait state; 0 = No Event, 1 = Event
Occurred. (Cleared by POLLMODE only).
Bit 7: Polling status; 0 = not active, 1 = active.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 93
BASIC Stamp Architecture – Constants and Expressions
Suppose you’re working on a program called “Three Cheers” that flashes
LEDs, makes hooting sounds, and activates a motor that crashes cymbals
together, all in sets of three. A portion of your PBASIC program might
contain something like:
CONSTANTS AND COMPILE-TIME
EXPRESSIONS.
1 All 2
FOR counter = 1 TO 3
GOSUB Make_Cheers
NEXT
...
FOR counter = 1 TO 3
GOSUB Blink_LEDs
NEXT
...
FOR counter = 1 TO 3
GOSUB Crash_Cymbals
NEXT
The numbers 1 and 3 in the code above are called constants. They are
constants because, while the program is running, nothing can happen to
change those numbers. This distinguishes constants from variables, which
can change while the program is running.
Constants are not limited to the decimal number system; PBASIC allows
you to use several numbering systems. See “Number Representations” on
page 96.
You can assign names to constants in a fashion similar to how variables
are declared. On a BS1, it is identical to variable declarations. For all BS2
models, use the CON directive. Here is the syntax:
SYMBOL
Name
=
ConstantValue
CON
ConstantValue
DEFINING AND USING CONSTANTS (CON).
1
-- or -Name
Page 94 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
All
2
4: BASIC Stamp Architecture – Constants and Expressions
Once created, named constants may be used in place of the numbers they
represent. For example:
1
SYMBOL
Cheers
=
3
' Number of cheers.
FOR counter = 1 TO Cheers
GOSUB Make_Cheers
NEXT
-- or -All
2
Cheers
CON
3
' Number of cheers.
FOR counter = 1 TO Cheers
GOSUB Make_Cheers
NEXT
That code works exactly the same as the corresponding FOR…NEXT loop
in the previous example. The editor software substitutes the number 3 for
the symbol named Cheers throughout your program. Like variables, labels
and instructions, constant names are not case sensitive; CHEERS, and
ChEErs are identical to Cheers.
Using named constants does not increase the amount of code downloaded
to the BASIC Stamp, and it often improves the clarity of the program.
Weeks after a program is written, you may not remember what a
particular number was supposed to represent—using a name may jog
your memory (or simplify the detective work needed to figure it out).
Named constants also have another benefit. Suppose the “Three Cheers”
program had to be upgraded to “Five Cheers.” In the original example
you would have to change all of the 3s to 5s. Search and replace would
help, but you might accidentally change some 3s that weren’t numbers of
cheers, too. However, if you had made smart use of a named constant, all
you would have to do is change 3 to 5 in one place, the constant's
declaration:
1
SYMBOL
Cheers
= 5
' Number of cheers.
-- or -All
2
Cheers
CON
5
' Number of cheers.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 95
BASIC Stamp Architecture – Number Representations
Now, assuming that you used the constant Cheers wherever your program
needed ‘the number of cheers,’ your upgrade would be done.
On all BS2 models, you can take this idea a step further by defining
constants with expressions; groups of math and/or logic operations that
the editor software solves (evaluates) at compile-time (the time right after
you start the download and before the BASIC Stamp starts running your
program). For example, suppose the “Cheers” program also controls a
pump to fill glasses with champagne. Perhaps the number of glasses to fill
is always twice the number of cheers, minus 1 (another constant):
All
2
Cheers
Glasses
All
2
CON
CON
5
Cheers*2-1
' # of cheers
' # of glasses
As you can see, one constant can be defined in terms of another. That is,
the number glasses depends on the number cheers.
The expressions used to define constants must be kept fairly simple. The
editor software solves them from left to right, and doesn’t allow you to use
parentheses to change the order of evaluation. The operators that are
allowed in constant expressions are shown in Table 4.5.
Operator Symbol
+
*
/
>
&
|
^
Description
Add
Subtract
Multiply
Divide
Shift Left
Shift Right
Logical AND
Logical OR
Logical XOR
Table 4.5: Operators allowed in
constant expressions for all BS2
models.
The BASIC Stamp, like any computer, excels at math and logic. However,
being designed for control applications, the BASIC Stamp does math a
little differently than a calculator or spreadsheet program. This section will
help you understand BASIC Stamp numbers, math, and logic.
RUN-TIME MATH AND LOGIC.
In your programs, you may express a number in various ways, depending
on how the number will be used and what makes sense to you. By default,
the BASIC Stamp recognizes numbers like 0, 99 or 62145 as being in our
NUMBER REPRESENTATIONS.
Page 96 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
1 All 2
4: BASIC Stamp Architecture – Number Representations
everyday decimal (base-10) system. However, you may also use
hexadecimal (base-16; also called hex) or binary (base-2).
Since the symbols used in decimal, hex and binary numbers overlap (e.g.,
1 and 0 are used by all; 0 through 9 apply to both decimal and hex) the
editor software needs prefixes to tell the numbering systems apart, as
shown below:
99
$1A6
%1101
' Decimal (no prefix)
' Hex (prefix ‘$’ required)
' Binary (prefix ‘%’ required)
The BASIC Stamp also automatically converts quoted text into ASCII
codes, and allows you to apply names (symbols) to constants from any of
the numbering systems. For example:
1
SYMBOL
SYMBOL
SYMBOL
SYMBOL
LetterA
Cheers
Hex128
FewBits
=
=
=
=
"A"
3
$80
%1101
' ASCII code for A (65)
-- or --
HEX TO BCD CONVERSION
All
2
LetterA
Cheers
Hex128
FewBits
All
2
Binary Coded Decimal (BCD) is a way to encode decimal digits that is
easier to display or manipulate in some devices. Each digit of the decimal
number (0 – 9) requires 4 bits (a nibble) to encode. For this reason, a BCD
byte is always two decimal digits and a BCD word is always four decimal
digits. The BASIC Stamp does not support BCD natively, however,
because of the way that BCD is encoded the BS2 models’ hexadecimal
prefix, and Conversion Formatters can be used as a shortcut for most BCD
input/output operations as long as the digits used do not exceed valid
decimal digits (0 – 9). For example:
BCDValue
DEBUG
HEX
CON
CON
CON
CON
"A"
3
$80
%1101
CON
' ASCII code for A (65)
$4096
BCDValue
The first line creates a symbol, BCDValue, that contains the binary form of
the hexadecimal value $4096, which means the upper nibble contains the
binary value for the decimal digit 4, the next nibble is 0, the next nibble is 9
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 97
BASIC Stamp Architecture – Number Representations
and the last nibble is 6; this corresponds exactly to the BCD form of the
decimal number 4096. The second line in the above example uses the HEX
Conversion Formatter within the DEBUG command (see DEBUG, page
159) to output the BCD value 4096 to the Debug Terminal. The HEX
Conversion Formatter can also be used for input operations to convert a
decimal value to BCD, as long as that decimal value is no greater than 2
digits for a Byte-sized variable or 4 digits for a Word-sized variable.
For more information on constants, see the section "Constants and
Compile-Time Expressions", above.
With all BS2 models, some of the math or logic operations in a program
are solved by the BASIC Stamp. The editor software solves operations that
define constants before the program is downloaded to the BASIC Stamp.
The preprocessing that takes place before the program is downloaded is
referred to as “compile-time.”
WHEN IS RUN-TIME?
All
2
All
2
After the download is complete, the BASIC Stamp starts executing your
program; this is referred to as “run-time.” At run-time the BASIC Stamp
processes math and logic operations involving variables, or any
combination of variables and constants.
Because compile-time and run-time expressions appear similar, it can be
hard to tell them apart.
A few examples will help:
result
VAR
Byte
' Compile-time assignment
Cheers
Glasses
OneNinety
NotWorking
CON
CON
CON
CON
3
Cheers * 2 - 1
100 + 90
3 * result
'
'
'
'
Compile-time
Compile-time
Compile-time
ERROR: Variables not allowed here
'
'
'
'
'
Run-time
Run-time
"100 + 90" solved at compile-time
OneNinety + 1 solved at run-time
100 + 90 solved at run-time
result = Glasses
result = 99 + Glasses
result = OneNinety + 1
result = 100 + 90
Notice that the last example is solved at run-time, even though the math
performed could have been solved at compile-time since it involves two
constants. If you find something like this in your own programs, you can
save some program space in the EEPROM by converting the run-time
Page 98 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
4: BASIC Stamp Architecture – PIN Symbols
expression 100+90 into a compile-time expression like OneNinety CON
100+90.
To sum up: compile-time expressions are those that involve only
constants; once a variable is involved, the expression must be solved at
run-time. That’s why the line “NotWorking CON 3 * result” would
generate an error message. The CON directive works only at compile-time
and result is a variable; variables are not allowed in compile-time
expressions.
DEFINING AND USING PINS WITH THE PIN
DIRECTIVE.
Now we know now to create variables and constants (with VAR and
All 2 CON) but there is a third option if you’re using PBASIC 2.5; pin-type
symbols (with PIN). PIN is like VAR and CON put together and
represents an I/O pin.
There are some situations where it is handy to refer to a pin using a
variable (like IN2 or OUT2) and also as a constant (2, in this case). The
PIN directive lets you define a context-sensitive symbol representing an
I/O pin. Depending on where and how this pin-type symbol is used
determines whether it is treated as an I/O pin input variable, and I/O pin
output variable or as a constant representing the pin number.
Let’s explore a simple example to see where this is useful. It is common
practice to define constants for any number used in many places so that
changing that number doesn’t create a maintenance hassle later on. If we
were to use a constant symbol to represent an I/O pin, we might do
something like this:
' {$PBASIC 2.5}
signal
INPUT
CON
1
signal
' constant-type symbol representing I/O 1
' set signal pin to input
Wait:
IF signal = 0 THEN Wait
' wait until signal pin = 1
Here we define signal to represent our desired I/O pin, then we use the
INPUT command to set it to the input direction and later we check the
state of the signal pin and loop (wait) while it is equal to logic 0. This code
has a common bug, however; the INPUT command works as expected,
because its Pin argument requires a number representing the I/O pin, but
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 99
BASIC Stamp Architecture – PIN Symbols
the Condition argument in the IF…THEN statement will always evaluate to
false because signal is a constant equal to 1, and “1 = 0” is false. What the
user really meant to happen is something like: IF IN1 = 0 THEN Wait
because IN1 is the input variable representing the current state of I/O pin
1. This situation is perfect for the PIN directive:
' {$PBASIC 2.5}
All
signal PIN 1
' pin-type symbol representing I/O 1
INPUT
' set signal pin to input
signal
Wait:
IF signal = 0 THEN Wait
' wait until signal = 1
We only changed one thing in this code: the CON directive was changed
to PIN. Now signal is a context-sensitive symbol that will be treated as a
constant or as a variable depending on where it is used. In the INPUT
command signal is used as the Pin argument, and since that argument
requires a number representing the pin number, signal is treated as a
constant equal to 1. In the IF…THEN statement, signal is compared to
another value (which implies that what signal represents is expected to
change at run-time; i.e.: signal’s value is “variable”) so signal is treated as a
variable equal to the input variable for the defined pin (IN1 in this case).
As another example, consider the following code:
' {$PBASIC 2.5}
signal
CON
OUTPUT signal
signal = 1
2
' constant-type symbol representing I/O 2
' set signal pin to output
' set signal high
Here, again, this is a common bug; the OUTPUT command will work as
expected, but the signal = 1 statement generates a syntax error at compiletime. Why the error? This is an assignment statement, meant to assign the
value 1 to the item on the left, but the item on the left is a constant, not a
variable, so it can not be changed at run-time. What the user was thinking
when writing this was: OUT2 = 1 which sets the value of the output
variable representing I/O pin 2 to logical 1 (high). Here’s the solution:
Page 100 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
2
4: BASIC Stamp Architecture – PIN Symbols
All
2
' {$PBASIC 2.5}
signal
PIN
2
OUTPUT signal
signal = 1
' pin-type symbol representing I/O 2
' set signal pin to output
' set signal high
The OUTPUT command treats signal as a constant equal to 2 and the
signal = 1 statement treats signal as a variable equal to the output variable
for the defined pin (OUT2 in this case).
You might be wondering why “signal = 0” in the IF…THEN statement of
our first example treats signal as the input variable IN1 and yet “signal =
1” in our last example treats signal as the output variable OUT2. The
distinction is that the first example is a comparison and the second
example is an assignment. Comparisons need to “read” expressions and
then evaluate the comparison while assignments need to read expressions
and then “write” the results. Since signal is to the left of the equal sign (=)
in our assignment statement, it must be a variable we can write to, thus it
must be treated as OUT2, in this case.
What happens if our pin-type symbol is to the right of the equal sign in an
assignment statement? Example:
All
2
' {$PBASIC 2.5}
signal1
signal2
PIN
PIN
1
2
INPUT signal1
OUTPUT signal2
signal2 = signal1
' pin-type symbol representing I/O 1
' pin-type symbol representing I/O 2
' set signal1 pin to input
' set signal2 pin to output
' set signal2 pin to signal1 pin’s state
In this case signal2 is treated as OUT2 and signal1 is treated as IN1; left side
must be written to and right side must be read from.
If a pin-type symbol is used in a command, but not in the Pin argument of
that command, it will be treated as an input variable (i.e.: INx). NOTE: It
is very rare that you’ll need to use a pin-type symbol in this way.
The following is a summary of behaviors and uses of pin-type symbols.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 101
BASIC Stamp Architecture – PIN Symbols
PIN_Symbol behaves like a constant:
1. when used in a command’s Pin argument. Example:
OUTPUT
2.
PIN_Symbol
when used in the index of an array. Example:
myArray(PIN_Symbol) = 25
PIN_Symbol behaves like an input variable (INx):
1. when used in a command’s non-Pin argument that expects to
read a variable/constant/expression. Example:
DEBUG BIN PIN_Symbol
2.
when used in a command’s Condition argument. Example:
IF PIN_Symbol = 1 THEN…
3.
when used to the right of the equal sign (=) in an assignment
statement. Example:
ex: myVariable = PIN_Symbol + 1
PIN_Symbol behaves like an output variable (OUTx):
1. when used in a command’s non-Pin argument that expects to
write a result to a variable. Example:
LOOKUP index, [0, 1, 1, 0, 1], PIN_Symbol
2.
when used to the left of the equal sign (=) in an assignment
statement. Example:
PIN_Symbol = 1
Let’s talk about the four basic operations of arithmetic: addition (+),
subtraction (-), multiplication (*), and division (/).
You may recall that the order in which you do a series of additions and
subtractions doesn’t affect the result. The expression 12+7-3+22 works out
the same as 22-3+12+7. However, when multiplication or division are
involved, it’s a different story; 12+3*2/4 is not the same as 2*12/4+3. In
fact, you may have the urge to put parentheses around portions of those
equations to clear things up.
Page 102 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
BASIC ARITHMETIC OPERATIONS
1 All 2
4: BASIC Stamp Architecture – Order of Operations
The BASIC Stamp solves math problems in the order they are written:
from left to right. The result of each operation is fed into the next
operation. So to compute 12+3*2/4, the BASIC Stamp goes through a
sequence like this:
ORDER OF OPERATIONS.
12 + 3 = 15
15 * 2 = 30
30 / 4 = 7
Since the BASIC Stamp performs integer math (whole numbers only) 30 /
4 results in 7, not 7.5. We’ll talk more about integers in the next section.
Some other dialects of BASIC would compute that same expression based
on their precedence of operators, which requires that multiplication and
division be done before addition. So the result would be:
3*2=6
6/4=1
12 + 1 = 13
Once again, because of integer math, the fractional portion of 6 / 4 is
dropped, so we get 1 instead of 1.5.
All
INTEGER MATH.
1
The BS1 does not allow parenthesis in expressions. Unfortunately, all
expressions have to be written so that they evaluate as intended strictly
from left to right.
2
All BS2 models, however, allow parentheses to be used to change the
order of evaluation. Enclosing a math operation in parentheses gives it
priority over other operations. To make the BASIC Stamp compute the
previous expression in the conventional way, you would write it as 12 +
(3*2/4). Within the parentheses, the BASIC Stamp works from left to right.
If you wanted to be even more specific, you could write 12 + ((3*2)/4).
When there are parentheses within parentheses, the BASIC Stamp works
from the innermost parentheses outward. Parentheses placed within
parentheses are called “nested parentheses."
The BASIC Stamp performs all math operations by the rules of positive
integer math. That is, it handles only whole numbers, and drops any
fractional portions from the results of computations. The BASIC Stamp
handles negative numbers using two's complement rules.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 103
BASIC Stamp Architecture – Math and Operators
All BS2 models can interpret twos complement negative numbers correctly
in DEBUG and SEROUT instructions using formatters like SDEC (for
signed decimal). In calculations, however, it assumes that all values are
positive. This yields correct results with two’s complement negative
numbers for addition, subtraction, and multiplication, but not for division.
The standard operators we just discussed: +, - ,* and / all work on two
values; as in 1 + 3 or 26 * 144. The values that operators process are
referred to as arguments. So we say that the add, subtract, multiply and
divide operators take two arguments.
All
2
UNARY AND BINARY OPERATORS.
Operators that take two arguments are called “binary” operators, and
those that take only one argument are called “unary” operators. Please
note that the term “binary operator” has nothing to do with binary
numbers; it’s just an inconvenient coincidence that the same word,
meaning ‘involving two things’ is used in both cases.
The minus sign (-) is a bit of a hybrid. It can be used as a binary operator,
as in 8-2 = 6, or it can be used as a unary operator to represent negative
numbers, such as -4.
Unary operators take precedence over binary operators; the unary
operation is always performed first. For example, on all BS2 models, SQR
is the unary operator for square root. In the expression 10 - SQR 16, the
BASIC Stamp first takes the square root of 16, then subtracts it from 10.
Most of the descriptions that follow say something like “computes (some
function) of a 16-bit value.” This does not mean that the operator does not
work on smaller byte or nibble values, but rather that the computation is
done in a 16-bit workspace. If the value is smaller than 16 bits, the BASIC
Stamp pads it with leading 0s to make a 16-bit value. If the 16-bit result of
a calculation is to be packed into a smaller variable, the higher-order bits
are discarded (truncated).
Keep this in mind, especially when you are working with two’s
complement negative numbers, or moving values from a larger variable to
a smaller one. For example, look at what happens when you move a two’s
complement negative number into a byte (rather than a word):
Page 104 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
NOTES ABOUT THE 16-BIT WORKSPACE.
4: BASIC Stamp Architecture – Math and Operators, ABS
All
2
value
VAR
Byte
value = - 99
DEBUG SDEC ?
1 All 2
value
' Show signed decimal result (157)
We expected -99 to be displayed but what we got was 157. How did -99
become 157? Let’s look at the bits: 99 is %01100011 binary. When the
BASIC Stamp negates 99, it converts the number to 16 bits
%0000000001100011, and then takes the two’s complement,
%1111111110011101. Since we’ve asked for the result to be placed in an 8bit (byte) variable, the upper eight bits are truncated and the lower eight
bits stored in the byte: %10011101.
Now for the second half of the story. DEBUG’s SDEC modifier (for all BS2
models) expects a 16-bit, two’s complement value, but we've only given it
a byte to work with. As usual, it creates a 16-bit value by padding the
leading eight bits with 0s: %0000000010011101. And what’s that in signed
decimal? 157.
To fix this problem, always store values that are intended to be signed into
a word-sized variable.
Table 4.1 lists the available Unary Operators. Note: the BS1 only supports
negative (-).
UNARY OPERATORS.
Table 4.1: Unary Operators.
Note: the BS1 only supports the
negative (-) unary operator.
Operator
ABS
COS
DCD
~
NCD
SIN
SQR
ABSOLUTE VALUE: ABS
All
2
Description
Returns absolute value
Returns cosine in twos complement
binary radians
n
2 -power decoder
Inverse
Negative
Priority encoder of a 16-bit value
Returns sine in twos complement
binary radians
Returns square root of value
Supported By:
All except BS1
All except BS1
All except BS1
All except BS1
All
All except BS1
All except BS1
All except BS1
The Absolute Value operator (ABS) converts a signed (two’s complement)
16-bit number to its absolute value. The absolute value of a number is a
positive number representing the difference between that number and 0.
For example, the absolute value of -99 is 99. The absolute value of 99 is
also 99. ABS works on two’s complement negative numbers. Examples of
ABS at work:
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 105
BASIC Stamp Architecture – COS, DCD, ~, result
VAR
Word
result = -99
'
'
'
'
DEBUG SDEC ? result
DEBUG SDEC ? ABS result
Put -99
...(2's
Display
Display
into result
complement format)
as a signed #
as a signed #
The Cosine operator (COS) returns the two’s complement, 16-bit cosine of
an angle specified as an 8-bit “binary radian” (0 to 255) angle. COS is the
same as SIN in all respects, except that the cosine function returns the x
distance instead of the y distance. See “Sine: SIN”, below, for a code
example and more information.
COSINE: COS
The Decoder operator (DCD) is a 2n-power decoder of a four-bit value.
DCD accepts a value from 0 to 15, and returns a 16-bit number with the
bit, described by value, set to 1. For example:
DECODER: DCD
result
VAR
result = DCD
DEBUG BIN16 ?
result
DEBUG
result
DEBUG
VAR
12
result
2
' Set bit 12
' Display result (%0001000000000000)
INVERSE: ~
Byte
= %11110001
BIN8 ? result
= ~ result
BIN8 ? Result
'
'
'
'
Store bits
Display in
Complement
Display in
in byte result.
binary (%11110001)
result
binary (%00001110)
The Negative operator (-) negates a 16-bit number (converts to its twos
complement).
SYMBOL
All
2
Word
The Inverse operator (~) complements (inverts) the bits of a number. Each
bit that contains a 1 is changed to 0 and each bit containing 0 is changed to
1. This process is also known as a “bitwise NOT” and “ones complement”.
For example:
result
All
result
result = -99
result = result + 100
DEBUG result
= W1
NEGATIVE: -
1
'
'
'
'
Put -99
...(2's
Add 100
Display
into result
complement format)
to it
result (1)
-- or -Page 106 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
4: BASIC Stamp Architecture – NCD, SIN
All
2
result
VAR
Word
result = 99
'
'
'
'
'
DEBUG SDEC ? result
result = -result
DEBUG SDEC ? result
ENCODER: NCD
All
2
The Encoder operator (NCD) is a "priority" encoder of a 16-bit value. NCD
takes a 16-bit value, finds the highest bit containing a 1 and returns the bit
position plus one (1 through 16). If the input value is 0, NCD returns 0.
NCD is a fast way to get an answer to the question “what is the largest
power of two that this value is greater than or equal to?” The answer NCD
returns will be that power, plus one. Example:
result
SINE: SIN
All
2
Put -99 into result
...(2's complement format)
Display as a signed #
Negate the value
Display as a signed #
VAR
result = %1101
DEBUG ? NCD result
Word
' Highest bit set is bit 3
' Show the NCD of result (4)The
Sine operator (SIN) returns the two’s complement, 16-bit sine of an angle
specified as an 8-bit binary radian (0 to 255) angle.
To understand the SIN operator more completely, let’s look at a typical
sine function. By definition: given a circle with a radius of 1 unit (known
as a unit circle), the sine is the y-coordinate distance from the center of the
circle to its edge at a given angle. Angles are measured relative to the 3o'clock position on the circle, increasing as you go around the circle
counterclockwise.
At the origin point (0 degrees) the sine is 0, because that point has the
same y (vertical) coordinate as the circle center. At 45 degrees the sine is
0.707. At 90 degrees, sine is 1. At 180 degrees, sine is 0 again. At 270
degrees, sine is -1.
The BASIC Stamp SIN operator breaks the circle into 0 to 255 units instead
of 0 to 359 degrees. Some textbooks call this unit a “binary radian” or
“brad.” Each brad is equivalent to 1.406 degrees. And instead of a unit
circle, which results in fractional sine values between 0 and 1, BASIC
Stamp SIN is based on a 127-unit circle. Results are given in two’s
complement form in order to accommodate negative values. So, at the
origin, SIN is 0. At 45 degrees (32 brads), sine is 90. At 90 degrees (64
brads), sine is 127. At 180 degrees (128 brads), sine is 0. At 270 degrees
(192 brads), sine is -127.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 107
BASIC Stamp Architecture – SIN, SQR
Figure 4.1: 127-Unit Circle
To convert brads to degrees, multiply by 180 then divide by 128, or simply
multiply with “*/ 360”. To convert degrees to brads, multiply by 128, then
divide by 180. Here’s a small program that demonstrates the SIN and COS
operators:
degr
brads
VAR Word
VAR Byte
DEBUG 2, 4, 0,"ANGLE", TAB, "COS", TAB, "SIN", CR
DEBUG "DEGREES", TAB,"BRADS", TAB, "(X)", TAB,"(Y)", CR
FOR degr = 0 TO 359 STEP 45
brads = degr * 128 / 180
DEBUG CR, DEC3 degr, TAB, DEC3 brads, TAB
DEBUG SDEC COS brads, TAB, SDEC SIN brads
NEXT
'
'
'
'
Increment degrees
Convert to brads
Display angle
Display COS & SIN
The Square Root operator (SQR) computes the integer square root of an
unsigned 16-bit number. (The number must be unsigned since the square
root of a negative number is an ‘imaginary’ number.) Remember that most
square roots have a fractional part that the BASIC Stamp discards when
Page 108 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
SQUARE ROOT: SQR
All
2
4: BASIC Stamp Architecture – +
doing its integer-only math. So it computes the square root of 100 as 10
(correct), but the square root of 99 as 9 (the actual is close to 9.95).
Example:
DEBUG ? SQR
DEBUG ? SQR
' Display square root of 100 (10)
' Display of square root of 99
' ...(9 due to truncation)
Table 4.6 lists the available Binary (two-argument) Operators.
BINARY OPERATORS.
Table 4.6: Binary Operators. Note:
some binary operators are not
supported by all BASIC Stamp
models.
ADD: +
100
99
1 All 2
Operator
+
*
**
*/
/
//
ATN
HYP
MIN
MAX
DIG
>
REV
&
|
^
&/
|/
^/
Description
Addition
Subtraction
Multiplication
Multiplication (returns upper 16-bits)
Multiply by 8-bit integer, 8-bit fraction
Division
Modulus (Remainder of division)
Returns arctangent of X/Y vector
Returns hypotenuse of X/Y vector
Limits a value to a specified low
Limits a value to a specified high
Returns specified digit of number
Shift bits left by specified amount
Shift bits right by specified amount
Reverse specified number of bits
Bitwise AND
Bitwise OR
Bitwise XOR
Logical AND NOT
Logical OR NOT
Logical XOR NOT
Supported By:
All
All
All
All
All BS2 models
All
All
All BS2 models
All BS2 models
All
All
All BS2 models
All BS2 models
All BS2 models
All BS2 models
All
All
All
BS1 Only
BS1 Only
BS1 Only
The Addition operator (+) adds variables and/or constants, returning a 16bit result. It works exactly as you would expect with unsigned integers
from 0 to 65535. If the result of addition is larger than 65535, the carry bit
will be lost. If the values added are signed 16-bit numbers and the
destination is a 16-bit variable, the result of the addition will be correct in
both sign and value.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 109
BASIC Stamp Architecture – +, -, *
For example:
SYMBOL
SYMBOL
value1
value2
value1
DEBUG
value1
value2
=
=
W0
W1
= - 99
= 100
= value1 + value2
value1
1
' Add the numbers
' Show the result (1)
-- or -value1
value2
value1
value2
value1
DEBUG
VAR
VAR
Word
Word
All
= - 1575
= 976
= value1 + value2
SDEC ? value1
' Add the numbers
' Show the result (-599)
The Subtraction operator (-) subtracts variables and/or constants,
returning a 16-bit result. It works exactly as you would expect with
unsigned integers from 0 to 65535. If the result is negative, it will be
correctly expressed as a signed 16-bit number. For example:
SYMBOL
SYMBOL
value1
value2
value1
DEBUG
value1
value2
=
=
W0
W1
= 199
= 100
= value1 - value2
value1
2
SUBTRACT: 1 All 2
1
' Subtract the numbers
' Show the result (99)
-- or -value1
value2
value1
value2
value1
DEBUG
VAR
VAR
Word
Word
= 1000
= 1999
= value1 - value2
SDEC ? value1
All
2
' Subtract the numbers
' Show the result (-999)
The Multiply operator (*) multiplies variables and/or constants, returning
the low 16 bits of the result. It works exactly as you would expect with
unsigned integers from 0 to 65535. If the result of multiplication is larger
than 65535, the excess bits will be lost. Multiplication of signed variables
will be correct in both number and sign, provided that the result is in the
range -32767 to +32767.
Page 110 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
MULTIPLY: *
1 All 2
4: BASIC Stamp Architecture – *, **
1
SYMBOL
SYMBOL
value1
value2
value1
DEBUG
value1
value2
=
=
W0
W1
= 1000
= 19
= value1 * value2
value1
' Multiply value1 by value2
' Show the result (19000)
VAR
VAR
= 1000
= - 19
= value1
SDEC ?
' Multiply value1 by value2
' Show the result (-19000)
-- or -All
MULTIPLY HIGH: **
2
1 All 2
1
value1
value2
value1
value2
value1
DEBUG
Word
Word
* value2
value1
The Multiply High operator (**) multiplies variables and/or constants,
returning the high 16 bits of the result. When you multiply two 16-bit
values, the result can be as large as 32 bits. Since the largest variable
supported by PBASIC is a word (16 bits), the highest 16 bits of a 32-bit
multiplication result are normally lost. The ** (double-star) instruction
gives you these upper 16 bits. For example, suppose you multiply 65000
($FDE8) by itself. The result is 4,225,000,000 or $FBD46240. The * (star, or
normal multiplication) instruction would return the lower 16 bits, $6240.
The ** instruction returns $FBD4.
SYMBOL
SYMBOL
value1
value2
=
=
W0
W1
value1 = $FDE8
value2 = value1 ** value1
DEBUG $value2
' Multiply $FDE8 by itself
' Return high 16 bits ($FBD4)
-- or -All
2
value1
value2
VAR
VAR
Word
Word
value1 = $FDE8
value2 = value1 ** value1
DEBUG HEX ? value2
' Multiply $FDE8 by itself
' Return high 16 bits ($FBD4)
An interesting application of the ** operator allows you no multiply a
number by a fractional value less than one. The fraction must be
expressed in units of 1/65536.
To find the fractional ** argument,
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 111
BASIC Stamp Architecture – **, */
multiply the fraction part by 65536. For example, 0.72562 is represented by
47554, which is 0.72562 * 65536.
SYMBOL
SYMBOL
Frac
value
= 47554
= W0
value = 10000
value = value ** Frac
DEBUG value
' = 0.72562 x 65536
1
' Multiply 10000 by 0.72562
' Show result (7256)
-- or –
Frac
value
CON
VAR
value = 10000
value = value ** Frac
DEBUG ? value
47554
Word
' = 0.72562 x 65536
VAR
Word
value1 = 100
value1 = value1*/ $0180
DEBUG ? value1
2
' Multiply 10000 by 0.72562
' Show result (7256)
The Multiply Middle operator (*/) multiplies variables and/or constants,
returning the middle 16 bits of the 32-bit result. This has the effect of
multiplying a value by a whole number and a fraction. The whole number
is the upper byte of the multiplier (0 to 255 whole units) and the fraction is
the lower byte of the multiplier (0 to 255 units of 1/256 each). The */ (starslash) instruction gives you an excellent workaround for the BASIC
Stamp's integer-only math. Suppose you want to multiply a value by 1.5.
The whole number, and therefore the upper byte of the multiplier, would
be 1, and the lower byte (fractional part) would be 128, since 128/256 = 0.5.
It may be clearer to express the */ multiplier in hex—as $0180—since hex
keeps the contents of the upper and lower bytes separate. Here's an
example:
value1
All
' Multiply by 1.5 [1 + (128/256)]
' Show result (150)
To calculate the constant for use with the */ operator, multiply the target
(mixed) value by 256 and convert to an integer. For instance, take Pi (π,
3.14159). The */ constant would be INT(3.14159 * 256) = 804 ($0324). So
the constant Pi for use with */ would be $0324. This isn’t a perfect match
for Pi, but the error is only about 0.1%. Note that the */ operator can be
used to multiply by mixed values up to about 255.996.
Page 112 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
MULTIPLY MIDDLE: */
All
2
All
2
4: BASIC Stamp Architecture – /, //
DIVIDE: /
1 All 2
1
The Divide operator (/) divides variables and/or constants, returning a
16-bit result. Works exactly as you would expect with unsigned integers
from 0 to 65535. Use / only with positive values; signed values do not
provide correct results. Here’s an example of unsigned division:
SYMBOL
value1
SYMBOL
value2
value1 = 1000
value2 = 5
=
=
W0
W1
value1 = value1 / value2
DEBUG value1
' Divide the numbers
' Show the result (200)
-- or -All
2
value1
value2
value1
value2
value1
DEBUG
VAR
VAR
Word
Word
= 1000
= 5
= value1 / value2
DEC ? value1
' Divide the numbers
' Show the result (200)
A workaround to the inability to divide signed numbers is to have your
program divide absolute values, then negate the result if one (and only
one) of the operands was negative. All values must lie within the range of
-32767 to +32767. Here is an example:
All
2
sign
value1
value2
VAR
VAR
VAR
Bit
Word
Word
' Bit to hold the result sign
value1 = 100
value2 = -3200
sign = value1.BIT15 ^ value2.BIT15
value2 = ABS value2 / ABS value1
IF (sign = 1) THEN value2 = -value2
DEBUG SDEC ? value2
MODULUS: //
1 All 2
'
'
'
'
Determine sign of result
Divide absolute values
Negate result if sign = 1
Show the result (-32)
The Modulus operator (//) returns the remainder left after dividing one
value by another. Some division problems don’t have a whole-number
result; they return a whole number and a fraction. For example, 1000/6 =
166.667. Integer math doesn’t allow the fractional portion of the result, so
1000/6 = 166. However, 166 is an approximate answer, because 166*6 =
996. The division operation left a remainder of 4. The // (double-slash)
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 113
BASIC Stamp Architecture – //, ATN
returns the remainder, 4 in this example. Naturally, numbers that divide
evenly, such as 1000/5, produce a remainder of 0.
Example:
SYMBOL
SYMBOL
value1
value2
= W0
= W1
value1 = 1000
value2 = 6
value1 = value1 // value2
DEBUG value1
' Get remainder of value1 / value2
' Show the result (4)
-- or -value1
value2
VAR
VAR
Word
Word
value1 = 1000
value2 = 6
value1 = value1 // value2
DEBUG ? value1
' Get remainder of value1 / value2
' Show the result (4)
The Arctangent operator (ATN) returns the angle to the vector specified
by X and Y coordinate values. The syntax of ATN is:
xCoord ATN yCoord
where xCoord and yCoord are the coordinates of the target vector point.
In the BASIC Stamp, the angle is returned in binary radians (0 to 255)
instead of degrees (0 to 359). See the explanation of the SIN operator for
more information about binary radians. Coordinate input values are
limited to -127 to 127 (signed bytes) as shown in the diagram of the
PBASIC Unit Circle (Figure 4.2).
brads
degr
VAR
VAR
brads = 4 ATN 4
degr = brads */ 360
DEBUG SDEC ? brads
DEBUG SDEC ? degr
Word
Word
' angle in brads
' angle in degrees
'
'
'
'
get angle
convert to degrees
display brads (32)
display degrees (45)
Page 114 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
ARCTANGENT: ATN
All
2
4: BASIC Stamp Architecture – ATN, HYP, MIN
Figure 4.2: ATN and HYP operators
in the PBASIC unit circle
HYPOTENUSE: HYP
All
2
The Hypotenuse operator (HYP) returns the length of the hypotenuse of a
right triangle with sides of length A and B. The syntax of HYP is:
SideA HYP SideB
where SideA and SideB are the side lengths of a right-triangle (the order
isn’t important). Another application of HYP is to calculate the distance
between the origin (0, 0) and a point (X, Y) in a Cartesian coordinate
system. Side length (vector) input values are limited to -127 to 127 (signed
bytes). See diagram with ATN operator, Figure 4.2.
DEBUG ? 3 HYP 4
MINIMUM: MIN
1 All 2
' hypotenuse of 3x4 triangle (5)
The Minimum operator (MIN) limits a value to a specified 16-bit positive
minimum. The syntax of MIN is:
value
MIN
limit
where value is a constant or variable value to perform the MIN function
upon and limit is the minimum value that value is allowed to be. Its logic
is, ‘if value is less than limit, then make result = limit; if value is greater than
or equal to limit, make result = value.’
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 115
BASIC Stamp Architecture – MIN, MAX
MIN works in positive math only; its comparisons are not valid when
used on two’s complement negative numbers, since the positive-integer
representation of a number like -1 ($FFFF or 65535 in unsigned decimal) is
larger than that of a number like 10 ($000A or 10 decimal). Use MIN only
with unsigned integers. Because of the way fixed-size integers work, you
should be careful when using an expression involving MIN 0. For
example, 0-1 MIN 0 will result in 65535 because of the way fixed-size
integers wrap around.
SYMBOL
SYMBOL
value1
value2
= W0
= W1
FOR value1 = 100 TO 0 STEP -10
value2 = value1 MIN 50
DEBUG value2
NEXT
1
' Walk value1 from 100 to 0
' Use MIN to clamp at 50
' Show "clamped" value
-- or -value
VAR
Word
FOR value = 100 TO 0 STEP 10
DEBUG ? value MIN 50
NEXT
All
The Maximum operator (MAX) limits a value to a specified 16-bit positive
maximum. The syntax of MAX is:
value
MAX
2
' Walk value from 100 to 0
' Show value1, use MIN to clamp at 50
Limit
Where value is a constant or variable value to perform the MAX function
upon and limit is the maximum value that value is allowed to be. Its logic
is, ‘if value is greater than limit, then make result = limit; if value is less than
or equal to limit, make result = value.’ MAX works in positive math only;
its comparisons are not valid when used on two’s complement negative
numbers, since the positive-integer representation of a number like -1
($FFFF or 65535 in unsigned decimal) is larger than that of a number like
10 ($000A or 10 decimal). Use MAX only with unsigned integers. Because
of the way fixed-size integers work, you should be careful when using an
expression involving MAX 65535. For example, 65535+1 MAX 65535 will
result in 0 because of the way fixed-size integers wrap around.
Page 116 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
MAXIMUM: MAX
1 All 2
4: BASIC Stamp Architecture – MAX, DIG,
1
SYMBOL
SYMBOL
value1
value2
= W0
= W1
FOR value1 = 0 TO 100 STEP 10
value2 = value1 MAX 50
DEBUG value2
NEXT
' Walk value1 from 0 to 100
' Use MAX to clamp at 50
' Show "clamped" value
-- or -All
2
value
VAR
Word
FOR value = 0 TO 100 STEP 10
DEBUG ? value MAX 50
NEXT
DIGIT: DIG
All
2
' Walk value from 0 to 100
' Show value, use MAX clamp at 50
The Digit operator (DIG) returns the specified decimal digit of a 16-bit
positive value. Digits are numbered from 0 (the rightmost digit) to 4 (the
leftmost digit of a 16-bit number; 0 to 65535).
Example:
value
idx
value =
DEBUG ?
FOR idx
DEBUG
NEXT
SHIFT LEFT: > idx
NEXT
' Repeat with idx = 1 to 16
' Shift value right idx places
The Reverse operator (REV) returns a reversed (mirrored) copy of a
specified number of bits of a value, starting with the right-most bit (least
significant bit or “lsb”). For instance, %10101101 REV 4 would return
%1011, a mirror image of the right-most four bits of the value. Example:
DEBUG
BIN4
?
%10101101
REV
4
REVERSE: REV
All
2
' Mirror 1st 4 bits (%1011)
The And operator (&) returns the bitwise AND of two values. Each bit of
the values is subject to the following logic:
AND: &
1 All 2
0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1
The result returned by & will contain 1s in only those bit positions in
which both input values contain 1s. Example:
SYMBOL
SYMBOL
SYMBOL
value1
value2
result
= B2
= B3
= B4
value1 = %00001111
value2 = %10101101
result = value1 & value2
DEBUG %result
1
' Show result of AND (%00001101)
-- or -DEBUG BIN8 ? %00001111 & %10101101
' Show result of AND (%00001101)
The OR operator (|) returns the bitwise OR of two values. Each bit of the
values is subject to the following logic:
Page 118 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
All
2
OR: |
1 All 2
4: BASIC Stamp Architecture – |, ^
0 OR 0 = 0
0 OR 1 = 1
1 OR 0 = 1
1 OR 1 = 1
The result returned by | will contain 1s in any bit positions in which one
or the other (or both) input values contain 1s. Example:
1
SYMBOL
SYMBOL
SYMBOL
value1
value2
result
= B2
= B3
= B4
value1 = %00001111
value2 = %10101001
result = value1 | value2
DEBUG %result
' Show result of OR (%10101111)
-- or -DEBUG
XOR: ^
All
2
BIN
?
%00001111
|
%10101001
' Show result of OR (%10101111)
The Xor operator (^) returns the bitwise XOR of two values. Each bit of the
values is subject to the following logic:
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
The result returned by ^ will contain 1s in any bit positions in which one
or the other (but not both) input values contain 1s. Example:
1
SYMBOL
SYMBOL
SYMBOL
value1
value2
result
= B2
= B3
= B4
value1 = %00001111
value2 = %10101001
result = value1 ^ value2
DEBUG %result
' Show result or XOR (%10100110)
-- or --
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 119
BASIC Stamp Architecture – &/, |/
DEBUG BIN8 ? %00001111 ^ %10101001
' Show result of XOR (%10100110)
The And Not operator (&/) returns the bitwise AND NOT of two values.
Each bit of the values is subject to the following logic:
All
2
AND NOT: &/
1
0 AND NOT 0 = 0
0 AND NOT 1 = 0
1 AND NOT 0 = 1
1 AND NOT 1 = 0
The result returned by &/ will contain 1s in any bit positions in which the
first value is 1 and the second value is 0. Example:
SYMBOL
SYMBOL
SYMBOL
value1
value2
result
= B2
= B3
= B4
value1 = %00001111
value2 = %10101001
result = value1 &/ value2
DEBUG %result
1
' Show result of AND NOT (%00000110)
The Or Not operator (|/) returns the bitwise OR NOT of two values. Each
bit of the values is subject to the following logic:
OR NOT: |/
1
0 OR NOT 0 = 1
0 OR NOT 1 = 0
1 OR NOT 0 = 1
1 OR NOT 1 = 1
The result returned by |/ will contain 1s in any bit positions in which the
first value is 1 or the second value is 0. Example:
SYMBOL
SYMBOL
SYMBOL
value1
value2
result
= B2
= B3
= B4
value1 = %00001111
value2 = %10101001
result = value1 |/ value2
DEBUG %result
1
' Show result of OR NOT (%01011111)
Page 120 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
4: BASIC Stamp Command Reference – ^/
XOR NOT: ^/
1
The Xor Not operator (^/) returns the bitwise XOR NOT of two values.
Each bit of the values is subject to the following logic:
0 XOR NOT 0 = 1
0 XOR NOT 1 = 0
1 XOR NOT 0 = 0
1 XOR NOT 1 = 1
The result returned by ^/ will contain 1s in any bit positions in which the
first value and second values are equal.
Example:
1
SYMBOL
SYMBOL
SYMBOL
value1
value2
result
= B2
= B3
= B4
value1 = %00001111
value2 = %10101001
result = value1 ^/ value2
DEBUG %result
' Show result of OR NOT (%01011001)
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 121
BASIC Stamp Architecture
Page 122 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference
Introduction
This chapter provides details on all three versions of the PBASIC
Programming Language. A categorical listing of all available PBASIC
commands is followed by an alphabetized command reference with
syntax, functional descriptions, and example code for each command.
PBASIC LANGUAGE VERSIONS
There are three forms of the PBASIC language: PBASIC 1.0 (for the BS1),
PBASIC 2.0 (for all BS2 models) and PBASIC 2.5 (for all BS2 models). You
may use any version of the language that is appropriate for your BASIC
Stamp module; however, when using any BS2 model, we suggest you use
PBASIC 2.5 for any new programs you write because of the advanced
control and flexibility it allows. PBASIC 2.5 is backward compatible with
almost every existing PBASIC 2.0-based program, and code that is not
100% compatible can easily be modified to work in PBASIC 2.5.
This chapter gives details on every command for every BASIC Stamp
model. Be sure to pay attention to any notes in the margins and body text
regarding supported models and PBASIC language versions wherever
they apply.
The BASIC Stamp Editor for Windows defaults to using PBASIC 1.0 (for
the BS1) or PBASIC 2.0 (for all BS2 models). If you wish to use the default
language for your BASIC Stamp model you need not do anything special.
If you wish to use PBASIC 2.5, you must specify that fact, using the
$PBASIC directive in your source code, for example:
' {$PBASIC 2.5}
Review the Compiler Directives section of Chapter 3 for more details on
this directive. Note: you may also specify either 1.0 or 2.0 using the
$PBASIC directive if you wish to explicitly state those desired languages.
Please note that the reserved word set will vary with each version of
PBASIC, with additional reserved words for some BASIC Stamp models.
Please see the reserved words tables in Appendix B for the complete lists.
PBASIC 2.5 features many enhancements. Table 5.1 gives a brief summary
of these items, with references to more information given elsewhere.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 123
BASIC Stamp Command Reference
Feature Categories
New Items
DEBUGIN,
Additional Commands
DO...LOOP, EXIT,
ON. SELECT...CASE
IF...THEN,
Enhanced Commands
GET, PUT,
READ, WRITE
Description
Allows easier user input and program
control. See individual command
descriptions.
Improves program control, and SPRAM and
EEPROM access. See individual command
descriptions.
Provides flexible, context-sensitive I/O pin
Additional Directive
PIN
references; see page 99.
Encourages development of source code
#DEFINE, #ERROR,
Conditional Compile
that is compatible with multiple BASIC
#IF...#THEN...#ELSE,
Directives
Stamp models and helpful user hints; see
#SELECT...CASE
page 70.
CLRDN, CLREOL,
CRSRDN, CRSRLF, Symbols for control characters supported by
Additional
CRSRRT, CRSRUP, the Debug Terminal. See Table 5.13 in the
Predefined Constants
CRSRX, CRSRXY, DEBUG command description, page 168.
CRSRY, LF
Any line can be continued to the next line
after the comma (,) character wherever
Syntax Enhancements
commas are normally used.
, and :
Colons are required on label declarations.
CATEGORICAL LISTING OF COMMANDS
This section lists all available PBASIC commands for all BASIC Stamp
models, grouped by category. Commands with PBASIC 2.5 enhanced
syntax options are marked with (*); commands that exist only in
PBASIC 2.5 are indicated with ( 2.5 ).
One or more of these icons indicates the item applies to
the BS1, BS2, BS2e, BS2sx, BS2p, BS2pe, or BS2px
respectively.
All
2 If an item applies to all of the models in the BS2 family,
this icon is used.
BRANCHING / PROGRAM CONTROL
1 All 2
BRANCH
Jump to address specified by offset.
1 All 2
IF...THEN*
Conditionally execute one or more blocks of code.
1 All 2
GOTO
Jump to address.
1 All 2
GOSUB
Jump to subroutine at address.
Page 124 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 5.1: PBASIC 2.5
Enhancements.
5: BASIC Stamp Command Reference
All
2 ON2.5
1 All 2
All
Jump to address or subroutine specified by an offset.
RETURN
Return from subroutine.
RUN
Switch execution to another program slot.
POLLRUN
Switch execution to another program page upon the
occurrence of a polled interrupt.
2 SELECT
…CASE2.5
All
2 STOP
Evaluate expression and conditionally execute a
block of code based on comparison to multiple
conditions.
Halt program execution until BASIC Stamp is reset.
LOOPING STRUCTURES
All
2 DO…LOOP2.5 Execute code block repetitively, with optional,
conditional exit.
All
2 EXIT2.5
1 All 2
FOR...NEXT
Terminate execution of a looping code block
(DO...LOOP or FOR...NEXT).
Execute code block repetitively, a finite number of
times using a counter.
EEPROM ACCESS
1
All
EEPROM
2 DATA
Store data in EEPROM during program download.
Store data in EEPROM during program download.
1 All 2
READ*
Read EEPROM value into variable.
1 All 2
WRITE*
Write value into EEPROM.
STORE
Switch READ/WRITE access to different program
slot.
RAM ACCESS
GET*
Read Scratch Pad RAM value into variable.
PUT*
Write value into Scratch Pad RAM.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 125
BASIC Stamp Command Reference
NUMERICS
1
LET
Optional
instruction
assignments.
to
perform
variable
1 All 2
LOOKUP
Look up data specified by offset and store in
variable. This instruction provides a means to make
a lookup table.
1 All 2
LOOKDOWN Find target’s matching value in table and store
match number (0-N) in variable.
1 All 2
RANDOM
Generate a pseudo-random number.
DIGITAL I/O
CONFIGPIN
Configure pin properties.
1 All 2
INPUT
Make pin an input.
1 All 2
OUTPUT
Make pin an output.
1 All 2
REVERSE
Reverse direction of a pin.
1 All 2
LOW
Make pin output low.
1 All 2
HIGH
Make pin output high.
1 All 2
TOGGLE
Make pin an output and toggle state.
1 All 2
PULSIN
Measure width of an input pulse.
1 All 2
PULSOUT
Output a pulse by inverting a pin for a given
amount of time.
1 All 2
BUTTON
Debounce button, perform auto-repeat, and branch
to address if button is in target state.
All
2 COUNT
Count cycles on a pin for a given amount of time.
All
2 XOUT
Generate X-10 power line control codes.
AUXIO
Switch control to auxiliary I/O pin group.
MAINIO
Switch control to main I/O pin group.
IOTERM
Switch control to specified I/O pin group.
POLLIN
Specify pin and state for a polled-interrupt.
POLLOUT
Specify pin and state for output upon a polledinterrupt.
POLLMODE
Specify the polled-interrupt mode.
Page 126 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference
ASYNCHRONOUS SERIAL I/O
1 All 2
SERIN
Input data in an asynchronous serial stream.
1 All 2
SEROUT
Output data in an asynchronous serial stream.
OWIN
Input data from a 1-wire device.
OWOUT
Output data to a 1-wire device.
SYNCHRONOUS SERIAL I/O
1 All 2
SHIFTIN
Shift data in from synchronous serial device.
1 All 2
SHIFTOUT
Shift data out to synchronous serial device.
I2CIN
Input data from I2C serial device.
I2COUT
Output data to I2C serial device.
PARALLEL I/O
LCDCMD
Write a command to an LCD.
LCDIN
Read data from an LCD.
LCDOUT
Write data to an LCD.
ANALOG I/O
1 All 2
1
All
PWM
Output using pulse width modulation, then return
pin to input.
POT
Read a 5 kΩ - 50 kΩ potentiometer and scale result.
2 RCTIME
Measure a variable resistance or capacitance.
COMPARE
Compare two 0-5 V analog voltages.
PAUSE
Pause execution for 0–65535 milliseconds.
POLLWAIT
Pause until a polled-interrupt occurs.
SOUND
Generate tones or white noise.
TIME
1 All 2
SOUND
1
All
2 FREQOUT
Generate one or two sine waves of specified
frequencies.
All
2 DTMFOUT
Generate DTMF telephone tones.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 127
BASIC Stamp Command Reference
POWER CONTROL
1 All 2
NAP
Nap for a short period. Power consumption is
reduced.
1 All 2
SLEEP
Sleep for 1-65535 seconds. Power consumption is
reduced.
1 All 2
END
Sleep until the power cycles or the PC connects.
Power consumption is reduced.
PROGRAM DEBUGGING
1 All 2
All
DEBUG
2 DEBUGIN2.5
Send information to the PC for viewing in the
Debug Terminal’s Receive windowpane.
Retrieve information from the user via the PC,
entered into the Debug Terminal’s Transmit
windowpane.
SYNTAX CONVENTIONS
BOLD UPPER CASE – any word that appears bold with all capital letters must
be typed exactly as shown. These are all reserved words.
Italics – italicized words must be replaced with your content.
[ ] – square brackets must be typed, in the position shown around the
given syntax element. Only used with PBASIC 2.0 and 2.5.
( ) – parentheses must be typed in the position shown around the given
syntax element; only used this way with PBASIC 1.0.**
{ } – curly braces indicate optional syntax items. They are not typed as part
of any syntax other than compiler directives.
| – vertical line separates mutually exclusive syntax elements.
, \ # = – where they appear, commas, backslashes, pound signs, and
equal signs must be typed in the positions shown.
**NOTE: You may use parentheses to enclose expressions in PBASIC 2.0 and 2.5, but they
are not necessary. Used within an expression, parentheses will change the order of
evaluation. See page 103 for details and examples.
Page 128 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – AUXIO
AUXIO
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
AUXIO
Function
Switch from control of main I/O pins to auxiliary I/O pins (on the BS2p40
only).
Quick Facts
Table 5.2: AUXIO Quick Facts.
I/O pin IDs
Special Notes
Related
Commands
BS2p, BS2pe, and BS2px
0 – 15 (just like main I/O, but after AUXIO command, all references affect
physical pins 21 – 36).
The BS2p, BS2pe, and BS2px 24-pin modules accept this command,
however, only the BS2p40 gives access to the auxiliary I/O pins.
MAINIO and IOTERM
Explanation
The BS2p, BS2pe, and BS2px are available as 24-pin modules that are pin
compatible with the BS2, BS2e and BS2sx. Also available is a 40-pin
module called the BS2p40, with an additional 16 I/O pins (for a total of
32). The BS2p40's extra, or auxiliary, I/O pins can be accessed in the same
manner as the main I/O pins (by using the IDs 0 to 15) but only after
issuing an AUXIO or IOTERM command. The AUXIO command causes
the BASIC Stamp to affect the auxiliary I/O pins instead of the main I/O
pins in all further code until the MAINIO or IOTERM command is
reached, or the BASIC Stamp is reset or power-cycled. AUXIO is also used
when setting the DIRS register for auxiliary I/O pins on the BS2p40.
When the BASIC Stamp module is reset, all RAM variables including DIRS
and OUTS are cleared to zero. This affects both main and auxiliary I/O
pins. On the BS2p24, BS2pe, and BS2px, the auxiliary I/O pins from the
interpreter chip are not connected to physical I/O pins on the BASIC
Stamp module. While not connected to anything, these pins do have
internal pull-up resistors activated, effectively connecting them to Vdd.
After reset, reading the auxiliary I/O from a BS2p24, BS2pe24, or BS2px24
will return all 1s.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 129
AUXIO - BASIC Stamp Command Reference
Here is a simple AUXIO example:
HIGH 0
AUXIO
LOW 0
A SIMPLE AUXIO EXAMPLE.
' make P0 high
' select auxiliary pins
' make X0 low
The first line of the above example will set I/O pin 0 of the main I/O pins
(P0, physical pin 5) high. Afterward, the AUXIO command tells the
BASIC Stamp that all commands following it should affect the auxiliary
I/O pins. The following LOW command will set I/O pin 0 of the auxiliary
I/O pins (X0, physical pin 21) low.
Note that the main I/O and auxiliary I/O pins are independent of each
other; the states of the main I/O pins remain unchanged while the
program affects the auxiliary I/O pins, and vice versa.
MAIN I/O AND AUXILIARY I/O PINS ARE
INDEPENDENT AND UNAFFECTED BY
CHANGES IN THE OPPOSITE GROUP.
Other commands that affect I/O group access are MAINIO and IOTERM.
2
Demo Program (AUX_MAIN_TERM.bsp)
p
' AUX_MAIN_TERM.bsp
' This program demonstrates the use of the AUXIO, MAINIO and IOTERM
' commands to affect I/O pins in the auxiliary and main I/O groups.
' {$STAMP BS2p}
' {$PBASIC 2.5}
#SELECT $STAMP
#CASE BS2, BS2E, BS2SX
#ERROR "Program requires BS2p40"
#CASE BS2P, BS2PE, BS2PX
DEBUG "Note: This program designed for the BS2p40.", CR
#ENDSELECT
port
VAR
Main:
DO
MAINIO
TOGGLE 0
PWM 1, 100, 40
AUXIO
TOGGLE 0
PULSOUT 1, 1000
PWM 2, 100, 40
Bit
' Switch to main I/O pins
' Toggle state of I/O pin P0
' Generate PWM on I/O pin P1
'
'
'
'
Switch to auxiliary
Toggle state of I/O
Generate a pulse on
Generate PWM on I/O
Page 130 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
I/O
pin
I/O
pin
pins
X0
pin X1
X2
NOTE: This example program will
tokenize with the 24-pin BS2p , BS2pe,
and BS2px, but its effects can only be
seen on the BS2p40. This program
uses conditional compilation techniques;
see Chapter 3 for more information.
5: BASIC Stamp Command Reference – AUXIO
IOTERM port
TOGGLE 3
port = ~port
PAUSE 1000
LOOP
END
'
'
'
'
'
'
Switch to main or aux I/Os
-- depending on port
Toggle state of I/O pin 3
-- on main and aux, alternately
Invert port
1 second delay
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 131
AUXIO - BASIC Stamp Command Reference
Page 132 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – BRANCH
BRANCH
1
All
2
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
BRANCH Offset, ( Address0, Address1, ...AddressN )
BRANCH Offset, [ Address0, Address1, ...AddressN ]
Function
1
NOTE: Expressions are not allowed as
arguments on the BS1.
Go to the address specified by offset (if in range).
• Offset is a variable/constant/expression (0 – 255) that specifies the
index of the address, in the list, to branch to (0 – N).
• Addresses are labels that specify where to go. BRANCH will ignore
any list entries beyond offset 255.
Quick Facts
Table 5.3: BRANCH Quick Facts.
Limit of
Address Entries
Related
Commands
BS1
All BS2 Models
Limited only by memory
256
None
ON...GOTO
Explanation
The BRANCH instruction is useful when you want to write something like
this:
IF value = 0 THEN Case_0
IF value = 1 THEN Case_1
IF value = 2 THEN Case_2
' when value is 0, jump to Case_0
' when value is 1, jump to Case_1
' when value is 2, jump to Case_2
1
You can use BRANCH to organize this into a single statement:
BS1 syntax not shown here.
BRANCH value, [Case_0, Case_1, Case_2]
This works exactly the same as the previous IF...THEN example. If the
value isn’t in range (in this case if value is greater than 2), BRANCH does
nothing and the program continues with the next instruction after
BRANCH.
BRANCH can be teamed with the LOOKDOWN instruction to create a
simplified SELECT...CASE statement. See LOOKDOWN for an example.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 133
BRANCH – BASIC Stamp Command Reference
Demo Program (BRANCH.bs1)
1
' BRANCH.bs1
' This program shows how the value of idx controls the destination of the
' BRANCH instruction.
' {$STAMP BS1}
' {$PBASIC 1.0}
SYMBOL
idx
= B2
Main:
DEBUG "idx: ", #idx, " "
BRANCH idx, (Task_0, Task_1, Task_2)
DEBUG "BRANCH target error...", CR, CR
Next_Task:
idx = idx + 1 // 4
GOTO Main
' branch to task
' ... unless out of range
' force idx to be 0..3
Task_0:
DEBUG "BRANCHed to Task_0", CR
GOTO Next_Task
Task_1:
DEBUG "BRANCHed to Task_1", CR
GOTO Next_Task
Task_2:
DEBUG "BRANCHed to Task_2", CR
GOTO Next_Task
Demo Program (BRANCH.bs2)
All
' BRANCH.bs2
' This program shows how the value of idx controls the destination of the
' BRANCH instruction.
' {$STAMP BS2}
' {$PBASIC 2.5}
idx
VAR
Nib
Main:
DEBUG "idx: ", DEC1 idx, " "
BRANCH idx, [Task_0, Task_1, Task_2]
DEBUG "BRANCH target error...", CR, CR
' branch to task
' ... unless out of range
Next_Task:
idx = idx + 1 // 4
' force idx to be 0..3
Page 134 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
2
NOTE: This example program can be
used with all BS2 models by changing
the $STAMP directive accordingly.
5: BASIC Stamp Command Reference – BRANCH
PAUSE 250
GOTO Main
Task_0:
DEBUG "BRANCHed to Task_0", CR
GOTO Next_Task
Task_1:
DEBUG "BRANCHed to Task_1", CR
GOTO Next_Task
Task_2:
DEBUG "BRANCHed to Task_2", CR
GOTO Next_Task
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 135
BRANCH – BASIC Stamp Command Reference
Page 136 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – BUTTON
BUTTON
1 All 2
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
BUTTON Pin, DownState, Delay, Rate, Workspace, TargetState, Address
Function
1
NOTE: Expressions are not allowed as
arguments on the BS1. The range of
the Pin argument on the BS1 is 0 – 7.
Monitor and process a pushbutton input, perform auto-repeat, and branch
to address if button is in target state. Button circuits may be active-low or
active-high.
• Pin is a variable/constant/expression (0–15) that specifies the I/O
pin to use. This pin will be set to input mode.
• DownState is a variable/constant/expression (0 or 1) that specifies
which logical state occurs when the button is pressed.
• Delay is a variable/constant/expression (0 – 255) that specifies how
long the button must be pressed before auto-repeat starts. The delay
is measured in cycles of the BUTTON routine. Delay has two special
settings: 0 and 255. If Delay is 0, BUTTON performs no debounce or
auto-repeat. If Delay is 255, BUTTON performs debounce, but no
auto-repeat.
• Rate is a variable/constant/expression (0 – 255) that specifies the
number of cycles between auto-repeats. The rate is expressed in
cycles of the BUTTON routine.
• Workspace is a byte variable used by BUTTON for workspace. It
must be cleared to 0 before being used by BUTTON for the first time
and should not be adjusted outside of the BUTTON command.
NOTE: All RAM is cleared to 0 by default upon power-up or reset
of the BASIC Stamp module.
• TargetState is a variable/constant/expression (0 or 1) that specifies
which state the button should be in for a branch to occur. (0=not
pressed, 1=pressed)
• Address is a label that specifies where to branch if the button is in the
target state.
Explanation
When you press a button or flip a switch, the contacts make or break a
connection. A brief (1 to 20-ms) burst of noise occurs as the contacts scrape
and bounce against each other. By scanning an input within a loop to
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 137
BUTTON – BASIC Stamp Command Reference
ensure that the contact remains in a specified state for a minimum
duration, spurious multiple inputs caused by contact noise can be
eliminated. The BUTTON instruction helps prevent this noise from being
interpreted as more than one switch action; this is the function of the Delay
parameter. For a demonstration of switch bounce, see the demo program
for the COUNT instruction. Delay, combined with the Rate argument,
allows the programmer to control the rate at which multiple inputs are
accepted by the BASIC Stamp.
BUTTON also lets PBASIC react to a button press the way your computer
keyboard does to a key press. When you press a key, a character
immediately appears on the screen. If you hold the key down, there’s a
delay, then a rapid-fire stream of characters appears on the screen.
BUTTON’s auto-repeat function can be set up to work much the same
way.
BUTTON is designed for use inside a program loop. Each time through
the loop, BUTTON checks the state of the specified pin. When it first
matches DownState, BUTTON begins the Delay countdown for auto-repeat.
Then, in accordance with TargetState, it either branches to Address
(TargetState = 1) or doesn’t (TargetState = 0).
If the switch stays in DownState, BUTTON counts the number of program
loops that execute. When this count equals Delay, BUTTON once again
triggers the action specified by TargetState and Address. Hereafter, if the
switch remains in DownState, BUTTON waits Rate number of cycles
between actions. The Workspace variable is used by BUTTON to keep
track of how many cycles have occurred since the Pin switched to
TargetState or since the last auto-repeat.
BUTTON does not stop program execution. In order for its delay and
auto-repeat functions to work properly, BUTTON must be executed from
within a program loop.
Page 138 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – BUTTON
Figure 5.1: Sample BUTTON
circuits. Active-high (left) and
active-low (right).
1
Demo Program (BUTTON.bs1)
'
'
'
'
'
'
'
BUTTON.bs1
Connect an active-low circuit to pin P0 of the BS1. When you press the
button, the DEBUG screen will display an asterisk (*). The program, as
shown below, will print an asterisk at the first button press, then
delay approximately one second (200 x 5 ms PAUSE) before auto-repeating
at a rate of approximately 100 ms (5 x 20 ms). Feel free to modify the
program to see the effects of your changes on the way BUTTON responds.
' {$STAMP BS1}
' {$PBASIC 1.0}
SYMBOL
Btn
= 0
SYMBOL
btnWrk
= B2
Main:
' Try changing the Delay value (200) in BUTTON to see the effect of
' its modes: 0 = no delay; 1-254 = varying delays before auto-repeat;
' 255 = no auto-repeat (only one action per button press)
'
' The BUTTON instruction will cause the program to branch to
' No_Press unless P0 = 0
PAUSE 5
BUTTON Btn, 0, 200, 20, btnWrk, 0, No_Press
DEBUG "*"
No_Press:
GOTO Main
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 139
BUTTON – BASIC Stamp Command Reference
Demo Program (BUTTON.bs2)
'
'
'
'
'
'
'
BUTTON.bs2
Connect an active-low circuit to pin P0 of the BS2. When you press the
button, the DEBUG screen will display an asterisk (*). The program, as
shown below, will print an asterisk at the first button press, then
delay approximately one second (200 x 5 ms PAUSE) before auto-repeating
at a rate of approximately 100 ms (5 x 20 ms). Feel free to modify the
program to see the effects of your changes on the way BUTTON responds.
' {$STAMP BS2}
' {$PBASIC 2.5}
Btn
PIN
0
btnWrk
VAR
Byte
Main:
' Try changing the Delay value (200) in BUTTON to see the effect of
' its modes: 0 = no delay; 1-254 = varying delays before auto-repeat;
' 255 = no auto-repeat (only one action per button press)
'
' The BUTTON instruction will cause the program to branch to
' No_Press unless P0 = 0
PAUSE 5
BUTTON Btn, 0, 200, 20, btnWrk, 0, No_Press
DEBUG "*"
No_Press:
GOTO Main
Page 140 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
All
2
NOTE: This example program can be
used with all BS2 models by changing
the $STAMP directive accordingly.
5: BASIC Stamp Command Reference – COMPARE
COMPARE
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
COMPARE Mode, Variable
Function
Enable or disable comparator, compare voltages on P1 and P2 and retrieve
comparison result to store in Variable.
• Mode is a variable/constant/expression (0 – 2) that enables or
disables the comparator (input pins P1 and P2) and determines if the
optional comparator output pin (pin P0) is enabled or not. See Table
5.4 for an explanation of the Mode values.
• Variable is a variable (usually a bit) in which the comparison result is
stored.
Quick Facts
Table 5.4: COMPARE Quick
Facts.
BS2px
0: Disables comparator
Mode Values 1: Enables comparator with P0 as result output
2: Enables comparator without P0 as result output
0: Voltage P1 > P2; P0 optionally outputs 0
Variable Values
1: Voltage P1 < P2; P0 optionally outputs 1
Explanation
The COMPARE command enables or disables the built-in comparator
hardware on the BS2px’s I/O pins P0, P1, and P2. I/O pins P1 and P2 are
the comparator inputs and P0 is optionally the comparator result output
pin.
By default, the comparator feature is disabled. Using the COMPARE
command with a Mode argument of 1 or 2 enables the comparator feature
(using input pins P1 and P2) and returns the result of the comparison in
Variable. If Mode is 1, the result of the comparison is also output on I/O
pin P0. The following is an example of the COMPARE command:
Result
COMPARE
VAR
1,
Bit
Result
This example enables the comparator (setting P0 to output the result, with
P1 and P2 as the comparator inputs) and writes the result of the
comparison into Result. Both Result and the output pin P0 will be 0 if the
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 141
COMPARE – BASIC Stamp Command Reference
input voltage on P1 was greater than that of P2. Result and the output pin
P0 will be 1 if the input voltage on P1 was less than that of P2.
Note that the comparator hardware operates independently of the
execution speed of the BS2px and will continue to run and update P0 if
Mode = 1, even during sleep mode (execution of END, NAP, POLLWAIT 8,
or SLEEP commands). To avoid spurious current draw during sleep
mode, disable the comparator first.
Demo Program (COMPARE.bpx)
'
'
'
'
'
'
COMPARE.bpx
This example demonstrates the use of the COMPARE command.
Connect two variable voltage sources (0 to 5 volts) on I/O pins
P1 and P2 (or a button on each pin connected to ground). Run the program
and watch the Debug Terminal display as you adjust the variable voltage
or press the buttons.
' {$STAMP BS2px}
' {$PBASIC 2.5}
Result VAR Bit
#IF $STAMP BS2PX #THEN
#ERROR "This program requires a BS2px."
#ENDIF
Setup:
CONFIGPIN DIRECTION, %0000000000000001
'P0 = output, all others = input
CONFIGPIN PULLUP,
%0000000000000110
'Enable pull-ups on P1 and P2
DEBUG "BS2px COMPARATOR DEMONSTRATION", CR,
"==============================", CR,
"Input Voltage: P1 > P2", CR,
"Output State: P0 = 0"
Main:
DO
COMPARE 1, Result
IF Result = 0 THEN
DEBUG CRSRXY,18,2,">"
ELSE
DEBUG CRSRXY,18,2," "
DEBUGIN DEC1 myNum
IF ((myNum >= 1) AND (myNum = 3)
' test after loop statements
The difference is that with this loop, the code block will always be run at
least once before the condition is tested and will continue to run as long as
the UNTIL condition evaluates as False.
Page 176 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – DO...LOOP
Note that the WHILE test (loop runs WHILE Condition is True) and UNTIL
test (loop runs UNTIL Condition is True) can be interchanged, but they are
generally used as illustrated above.
All
2
NOTE: This example program can be
used with all BS2 models by changing
the $STAMP directive accordingly.
Demo Program (DO-LOOP.bs2)
'
'
'
'
'
'
DO-LOOP.bs2
This program creates a little guessing game. It starts by creating
a (pseudo) random number between 1 and 10. The inner loop will run
until the answer is guessed or 10 tries have been attempted. The
outer loop has no condition and will cause the inner loop code to
run until the BASIC Stamp is reprogrammed.
' {$STAMP BS2}
' {$PBASIC 2.5}
rVal
answer
guess
tries
VAR
VAR
VAR
VAR
Word
Byte
Byte
Nib
Main:
DO
RANDOM rVal
answer = rVal.LOWBYTE */ 10 + 1
tries = 0
'
'
'
'
random value
game answer
player guess
number of tries
' create 1 - 10 answer
DO
' get answer until out of tries
DEBUG CLS,
"Guess a number (1 - 10): "
DEBUGIN DEC guess
' get new guess
tries = tries + 1
' update tries count
LOOP UNTIL ((tries = 10) OR (guess = answer))
IF (guess = answer) THEN
' test reason for loop end
DEBUG CR, "You got it!"
ELSE
DEBUG CR, "Sorry ... the answer was ", DEC answer, "."
ENDIF
PAUSE 1000
LOOP
' run again
END
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 177
DO...LOOP – BASIC Stamp Command Reference
Page 178 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – DTMFOUT
DTMFOUT
All
2
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
DTMFOUT Pin, { OnTime, OffTime, } [ Tone {, Tone…} ]
Function
Generate dual-tone, multifrequency tones (DTMF, i.e., telephone “touch”
tones).
• Pin is a variable/constant/expression (0 – 15) that specifies the I/O
pin to use. This pin will be set to output mode during generation of
tones and set to input mode afterwards.
• OnTime is an optional variable/constant/expression (0 – 65535)
specifying a duration of the tone. The unit of time and the default
time for OnTime is described in Table 5.19.
• OffTime is an optional variable/constant/expression (0 – 65535)
specifying the length of silent pause after a tone (or between tones, if
multiple tones are specified). The unit of time and the default time
for OffTime is described in Table 5.19.
• Tone is a variable/constant/expression (0 – 15) specifying the DTMF
tone to generate. Tones 0 through 11 correspond to the standard
layout of the telephone keypad, while 12 through 15 are the fourthcolumn tones used by phone test equipment and in ham-radio
applications.
Quick Facts
Table 5.19: DMTFOUT Quick Facts.
Default OnTime
Default OffTime
Units in OnTime
Units in OffTime
Related Command
BS2, BS2e
200 ms
50 ms
1 ms
1 ms
BS2sx
80 ms
50 ms
0.4 ms
1 ms
BS2p
55 ms
50 ms
0.265 ms
1 ms
FREQOUT
BS2pe
196 ms
50 ms
1 ms
1 ms
BS2px
34 ms
50 ms
0.166 ms
1 ms
Explanation
DTMF tones are used to dial the phone or remotely control certain radio
equipment. The BASIC Stamp can generate these tones digitally using the
DTMFOUT instruction. Figure 5.4 shows how to connect a speaker or
audio amplifier to hear these tones and Figure 5.5 shows how to connect
the BASIC Stamp to the phone line.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 179
DTMFOUT – BASIC Stamp Command Reference
The following DTMFOUT instruction will generate DTMF tones on I/O
pin 10:
DTMFOUT 10, [6, 2, 4, 8, 3, 3, 3]
' Call Parallax
If the BASIC Stamp is connected to the phone line properly, the above
command would be equivalent to dialing 624-8333 from a phone keypad.
If you wanted to slow the pace of the dialing to accommodate a noisy
phone line or radio link, you could use the optional OnTime and OffTime
values:
DTMFOUT 10, 500, 100, [ 6, 2, 4, 8, 3, 3, 3]
' Call Parallax, slowly
In this example, on a BS2 the OnTime is set to 500 ms (1/2 second) and
OffTime to 100 ms (1/10th second).
Tone Value
0–9
10
11
12 – 15
Corresponding Telephone Key
Digits 0 through 9
Star (*)
Pound (#)
Fourth column tones A through D
Driving an Audio Amplifier
1k
1k
Amplifier
(e.g., Radio Shack
from I/O pin
0.01µF
0.1µF
Vss
277-1008C)
Vss
Vss
Driving a Speaker
10µF (both)
from I/O pin
+
C1
+
C2
≥40Ω Speaker
(or 8Ω in series
with 33Ω resistor)
Vss
Vss
Notes:
C1 may be omitted for piezo speakers
C2 is optional, but reduces high-frequency noise
Page 180 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 5.20: DTMF Tones and
Corresponding Telephone Keys.
Figure 5.4: Example RC Filter
Circuits for Driving an Audio
Amplifier (top) or a Speaker
(bottom).
5: BASIC Stamp Command Reference – DTMFOUT
The BASIC Stamp microcontroller is a purely digital device. DTMF tones
are analog waveforms, consisting of a mixture of two sine waves at
different audio frequencies. So how does a digital device generate analog
output? The BASIC Stamp creates and mixes the sine waves
mathematically, then uses the resulting stream of numbers to control the
duty cycle of a very fast pulse-width modulation (PWM) routine. So
what’s actually coming out of the I/O pin is a rapid stream of pulses. The
purpose of the filtering arrangements shown in Figure 5.4 and Figure 5.5 is
to smooth out the high-frequency PWM, leaving only the lower frequency
audio behind.
TECHNICAL BACKGROUND.
Keep this in mind if you want to interface BASIC Stamp's DTMF output to
radios and other equipment that could be adversely affected by the
presence of high-frequency noise on the input. Make sure to filter the
DTMF output thoroughly. The circuits in Figure 5.4 are only a starting
point; you may want to use an active low-pass filter with a roll-off point
around 2 kHz.
Figure 5.5: Example DAA Circuit to
Interface to a Standard Telephone
Line.
Interfacing to the Telephone Line
connect switch (or
relay contacts)
phone line
(red and green)
600-600Ω
transformer
(JC: 117760)
10Ω
(both)
270V “Sidactor”
(DK: P3000AA61-ND
P3000AA61-ND)
Digi-Key (DK), 1-800-344-4539
or 218-681-6674
All
2
NOTE: This example program can be
used with all BS2 models. This program
uses conditional compilation techniques;
see Chapter 3 for more information.
1 kΩ 0.1µF
from I/O pin
0.001µF
3.9V zeners (both)
DK: 1N5228BCT-ND
Vss
Jameco (JC), 1-800-831-4242
or 415-592-8097
Demo Program (DTMFOUT.bs2)
'
'
'
'
'
'
'
DTMFOUT.bs2
This demo program is a rudimentary memory dialer. Since DTMF digits fit
within a nibble (four bits), the program below packs two DTMF digits into
each byte of three EEPROM data tables. The end of phone number is marked
by the nibble $F, since this is not a valid phone-dialing digit.
Conditional compilation sets the timing adjustment factor so that the
output will sound the same on any BS2 model.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 181
DTMFOUT – BASIC Stamp Command Reference
' {$STAMP BS2}
' {$PBASIC 2.5}
Spkr
PIN
10
#SELECT $STAMP
#CASE BS2, BS2E, BS2PE
TmAdj
CON
$100
#CASE BS2SX
TmAdj
CON
$280
#CASE BS2P
TmAdj
CON
$3C5
#CASE BS2PX
TmAdj
CON
$607
#ENDSELECT
' DTMF output on pin 10
' x 1.0 (time adjust)
' x 2.5
' x 3.77
' x 6.03
eeLoc
eeByte
dtDig
phone
hiLo
VAR
VAR
VAR
VAR
VAR
Byte
Byte
eeByte.NIB1
Nib
Bit
'
'
'
'
'
EEPROM address of stored number
Byte containing two DTMF digits
Digit to dial
Pick a phone #
Bit to select upper and lower nib
Parallax
ParallaxFax
Information
DATA
DATA
DATA
$19,$16,$62,$48,$33,$3F
$19,$16,$62,$48,$00,$3F
$15,$20,$55,$51,$21,$2F
' Phone: 1-916-624-8333
' Phone: 1-916-624-8003
' Phone: 1-520-555-1212
Main:
FOR phone = 0 TO 2
' retrieve address
LOOKUP phone, [Parallax, ParallaxFax, Information], eeLoc
GOSUB Dial_Number
PAUSE 2000
NEXT
END
Dial_Number:
DO
READ eeLoc, eeByte
'
eeLoc = eeLoc + 1
'
FOR hiLo = 0 TO 1
'
IF (dtDig = $F) THEN EXIT
'
DTMFOUT Spkr,
'
150 */ TmAdj, 25, [dtDig] '
eeByte = eeByte 9) THEN EXIT
DEBUG CRSRXY, (col * 8), row,
DEC col, "/", DEC row, CR
NEXT
col = col + 1
IF (col = 3) THEN EXIT
LOOP
END
'
'
'
'
attempt 10 iterations
attempt 16 iterations
terminate when row > 9
print col/row at location
' update column
' terminate when col = 3
Page 190 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – FOR...NEXT
FOR…NEXT
1
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
FOR Counter = StartValue TO EndValue { STEP {-} StepValue }
Statement(s)
NEXT { Counter }
All
2
FOR Counter = StartValue TO EndValue { STEP StepValue }
Statement(s)
NEXT { Counter }
Function
1
NOTE: Expressions are not allowed as
arguments on the BS1.
1
NOTE: Use a minus sign to indicate
negative StepValues on the BS1.
Create a repeating loop that executes the Statement(s), one or more
program lines that form a code block, between FOR and NEXT,
incrementing or decrementing Counter according to StepValue until the
value of the Counter variable passes the EndValue.
• Counter is a variable (usually a byte or a word) used as a counter.
• StartValue is a variable/constant/expression (0 – 65535) that
specifies the initial value of the variable (Counter).
• EndValue is a variable/constant/expression (0 – 65535) that specifies
the end value of the variable (Counter). When the value of Counter is
outside of the range StartValue to EndValue, the FOR...NEXT loop
stops executing and the program goes on to the instruction after
NEXT.
• StepValue is an optional variable/constant/expression (0 – 65535) by
which the Counter increases or decreases with each iteration through
the FOR…NEXT loop. On the BS1, use a minus sign (-) in front of
the StepValue to indicate a negative step. On all BS2 models, if
StartValue is larger than EndValue, PBASIC understands StepValue to
be negative, even though no minus sign is used.
• Statement is any valid PBASIC instruction.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 191
FOR…NEXT – BASIC Stamp Command Reference
Quick Facts
BS1
All BS2 Models
8
16
Set StartValue > EndValue and
Set StartValue > EndValue
enter negative StepValue*
Exit loop if Counter exceeds
Exit loop if Counter outside range
Counter Comparison
EndValue
set by StartValue to EndValue
None
DO...LOOP and EXIT
Related Commands
*NOTE: For the BS1, direction (increment or decrement) cannot be changed at run-time.
Max. Nested Loops
To Decrement
Counter Variable
Table 5.25: FOR...NEXT Quick
Facts.
Explanation
FOR...NEXT loops let your program execute a series of instructions for a
specified number of repetitions (called iterations). By default, each time
through the loop, the Counter variable is incremented by 1. It will continue
to loop until the value of Counter is outside of the range set by StartValue
and EndValue. Also, FOR…NEXT loops always execute at least once. The
simplest form is shown here:
SIMPLEST FORM OF FOR...NEXT.
1
NOTE: On the BS1, the loop will
continue until Counter has gone
past EndValue.
reps
NOTE: Replace the first line with
SYMBOL reps = B0
on the BS1.
VAR
Nib
FOR reps = 1 TO 3
DEBUG "*"
NEXT
' counter for the FOR/NEXT loop
' repeat with reps = 1, 2, 3
' put * on screen for each repetition
In the above code, the FOR command sets reps = 1. Then the DEBUG line
(within the FOR…NEXT loop) is executed; printing an asterisk (*) on the
screen. When the BASIC Stamp sees the NEXT command, it goes back to
the previous FOR command, adds 1 to reps and compares the result to the
range set by StartValue and EndValue. If reps is still within range, it
executes the code in the loop again. Each time the FOR...NEXT loop
executes, the value of reps is updated (incremented by 1) and the code
within the loop (the DEBUG line) is executed; printing another asterisk on
the screen. This code will run through the loop three times; setting reps to
1, 2 and 3, and printing three asterisks on the screen. After the third loop,
again the BASIC Stamp goes back up to the FOR command, adds 1 to reps
and compares the result (4 in this case) to the range. Since the range is 1 to
3 and the value is 4 (outside the range) the FOR…NEXT loop is done and
the BASIC Stamp will jump down to the first line of code following the
NEXT command.
You can view the changing values of reps by including the reps variable in
a DEBUG command within the loop:
Page 192 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
1
PROCESSING A FOR…NEXT LOOP.
5: BASIC Stamp Command Reference – FOR...NEXT
NOTE: Change the first line as noted 1
above and replace line 3 with
DEBUG #Reps, CR
reps
VAR
Nib
FOR reps = 1 TO 3
DEBUG DEC reps, CR
NEXT
' counter for the FOR/NEXT loop
' repeat with reps = 1, 2, 3
' print rep number
Running this example should display "1" , "2", and "3" on the screen.
FOR…NEXT can also be made to decrement (rather than increment) the
Counter variable. The BS1 does this when you specify a negative StepValue
(as well as a StartValue that is greater than the EndValue). All other BASIC
Stamp models do this automatically when the StartValue is greater than
the EndValue. Examples of both are shown below:
DECREMENTING THE COUNTER INSTEAD
OF INCREMENTING IT.
1
SYMBOL
reps
= B0
FOR reps = 3 TO 1 STEP -1
DEBUG #reps, CR
NEXT
' counter for the FOR/NEXT loop
' repeat with reps = 3, 2, 1
' print reps number
-- or -All
2
reps
VAR
Nib
FOR reps = 3 TO 1
DEBUG DEC reps, CR
NEXT
' counter for the FOR/NEXT loop
' repeat with reps = 3, 2, 1
' print reps number
All
2
Note that the code for all the BS2 models did not use the optional STEP
argument. This is because we wanted to decrement by positive 1 anyway
(the default unit) and the BASIC Stamp realizes it needs to decrement
because the StartValue is greater than the EndValue. A negative StepValue
on any BS2 model would be treated as its positive, twos complement
counterpart. For example, –1 in twos complement is 65535. So the
following code executes only once:
All
2
reps
VAR
Nib
FOR reps = 3 TO 1 STEP -1
DEBUG DEC reps, CR
NEXT
' counter for the FOR/NEXT loop
' try to decrement 3 by 65535
' print reps number
The above code would run through the loop once with reps set to 3. The
second time around, it would decrement reps by 65535 (-1 is 65535 in twos
complement) effectively making the number –65532 (4 in twos
complement) which is outside the range of the loop.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 193
FOR…NEXT – BASIC Stamp Command Reference
All the arguments in the FOR…NEXT command can be constants,
variables or expressions on all BS2 models. This leads to some interesting
uses. For example, if you make the StartValue and EndValue a variable,
and change their values within the loop, you'll change the behavior of the
loop itself. Try the following:
{' $PBASIC 2.5}
reps
startVal
endVal
USING VARIABLES AS ARGUMENTS.
All
VAR
VAR
VAR
Byte
Byte
Byte
2
' counter for the FOR/NEXT loop
1
startVal = 1
endVal = 3
' initialize startVal to 1
' initialize endVal to 3
FOR reps = startVal TO endVal
DEBUG DEC reps, CR
IF (reps = 3) THEN
startVal = 3
endVal = 1
ENDIF
NEXT
' repeat for 1 to 3
NOTE: The increment/decrement
direction of the FOR…NEXT loop
cannot be changed on the BS1.
' if reps =3, swap startVal/endVal
' otherwise continue loop
Here the loop starts with a range of 1 to 3. First, the DEBUG line prints the
value of reps. Then the IF…THEN line makes a decision; if reps is equal to
3, then swap the order of startVal and endVal, otherwise continue the loop
execution. The next time through the loop (after startVal and endVal have
been swapped), reps will be decremented instead of incremented because
startVal is greater than endVal. The result is a display on the screen of the
numbers 1, 2, 3, 2, 1.
The following example uses the value of reps as the StepValue. This creates
a display of power's of 2 (1, 2, 4, 8, 16, 32, 64, etc):
reps
VAR
Word
FOR reps = 1 TO 256 STEP reps
DEBUG DEC ? reps
NEXT
' counter for the loop
' each loop add current value of reps
' show reps in Debug window
There is a potential bug that you should be careful to avoid. The BASIC
Stamp uses unsigned 16-bit integer math for any math operation it
performs, regardless of the size of values or variables. The maximum
value the BASIC Stamp can internally calculate is 65535 (the largest 16-bit
Page 194 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
1
NOTE: For BS1's, change line 1 to
SYMBOL reps = W0
and line 3 to
DEBUG reps
WATCH OUT FOR 16-BIT ROLLOVER, OR
VARIABLE RANGE, ERRORS.
5: BASIC Stamp Command Reference – FOR...NEXT
number). If you add 1 to 65535, you get 0 as the 16-bit register rolls over
(like a car’s odometer does when you exceed the maximum mileage it can
display). Similarly, if you subtract 1 from 0, you'll get 65535 as the 16-bit
register rolls under (a rollover in the opposite direction).
If you write a FOR...NEXT loop who's StepValue would cause Counter to go
past 65535, this rollover may cause the loop to execute more times than
you expect. Try the following example:
1
reps
NOTE: For BS1's, change line 1 to
SYMBOL reps = W0
and line 3 to
DEBUG reps
VAR
Word
FOR reps = 0 TO 65535 STEP 3000
DEBUG DEC ? reps
NEXT
' counter for the loop
' each loop add 3000
' show reps in Debug window
The value of reps increases by 3000 each trip through the loop. As it
approaches the EndValue, an interesting thing happens; reps is: 57000,
60000, 63000, 464, 3464... It passes the EndValue, rolls over and keeps
going. That’s because the result of the calculation 63000 + 3000 exceeds the
maximum capacity of a 16-bit number and then rolls over to 464. When
the result of 464 is tested against the range (“Is Reps > 0 and is Reps <
65535?”) it passes the test and the loop continues.
A similar symptom can be seen in a program who's EndValue is mistakenly
set higher than what the counter variable can hold. The example below
uses a byte-sized variable, but the EndValue is set to a number greater than
what will fit in a byte:
SYMBOL
reps
= B2
FOR reps = 0 TO 300
DEBUG reps
NEXT
' counter for the loop
' each loop add 1
' show reps in Debug window
1
-- or -All
2
reps
VAR
Byte
FOR reps = 0 TO 300
DEBUG DEC ? reps
NEXT
' counter for the loop
' each loop add 1
' show reps in Debug window
Here, reps is a byte variable; which can only hold the number range 0 to
255. The EndValue is set to 300, however; greater than 255. This code will
loop endlessly because when reps is 255 and the FOR…NEXT loop adds 1,
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 195
FOR…NEXT – BASIC Stamp Command Reference
reps becomes 0 (bytes will rollover after 255 just like words will rollover
after 65535). The result, 0, is compared against the range (0 – 255) and it is
found to be within the range, so the FOR…NEXT loop continues.
It's important to realize that on all the BS2 models, the test is against the
entire range, not just the EndValue. The code below is a slight modification
of the previous example (the StartValue is 10 instead of 0) and will not loop
endlessly.
reps
VAR
Byte
' counter for the loop
FOR reps = 10 TO 300
DEBUG DEC ? reps
NEXT
NOTE: On the BS1, the loop will
continue until Counter has gone past
EndValue. The rollover error will still
occur if the BS1 cannot determine if
Counter went past EndValue.
All
' each loop add 1
' show reps in Debug window
reps still rolls over to 0, as before, however, this time it is outside the range
of 10 to 255. The loop stops, leaving reps at 0. Note that this code is still in
error since reps will never reach 300 until it is declared as a Word.
Demo Program (FOR-NEXT.bs1)
'
'
'
'
'
'
1
FOR-NEXT.bs1
This example uses a FOR...NEXT loop to churn out a series of sequential
squares (numbers 1, 2, 3, 4... raised to the second power) by using a
variable to set the FOR...NEXT StepValue, and incrementing StepValue
within the loop. Sir Isaac Newton is generally credited with the
discovery of this technique.
' {$STAMP BS1}
' {$PBASIC 1.0}
SYMBOL
SYMBOL
square
stepSize
= B2
= B3
' FOR/NEXT counter
' step size increases by 2 each loop
Setup:
stepSize = 1
square = 1
Main:
FOR square = 1 TO 250 STEP stepSize
DEBUG square
stepSize = stepSize + 2
NEXT
END
'
'
'
'
show squares up to 250
display on screen
add 2 to stepSize
loop until square > 250
Page 196 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
2
5: BASIC Stamp Command Reference – FOR...NEXT
All
2
NOTE: This example program can be
used with all BS2 models by changing
the $STAMP directive accordingly.
Demo Program (FOR-NEXT.bs2)
'
'
'
'
'
'
FOR-NEXT.bs2
This example uses a FOR...NEXT loop to churn out a series of sequential
squares (numbers 1, 2, 3, 4... raised to the second power) by using a
variable to set the FOR...NEXT StepValue, and incrementing StepValue
within the loop. Sir Isaac Newton is generally credited with the
discovery of this technique.
' {$STAMP BS2}
' {$PBASIC 2.5}
square
stepSize
VAR
VAR
Byte
Byte
' FOR/NEXT counter
' step size increases by 2 each loop
Setup:
stepSize = 1
square = 1
Main:
FOR square = 1 TO 250 STEP stepSize
DEBUG DEC ? square
stepSize = stepSize + 2
NEXT
END
'
'
'
'
show squares up to 250
display on screen
add 2 to stepSize
loop until square > 250
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 197
FOR…NEXT – BASIC Stamp Command Reference
Page 198 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – FREQOUT
FREQOUT
1
All
2
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
(See SOUND)
FREQOUT Pin, Duration, Freq1 { , Freq2 }
Function
Generate one or two sine-wave tones for a specified Duration.
• Pin is a variable/constant/expression (0 – 15) that specifies the I/O
pin to use. This pin will be set to output mode.
• Duration is a variable/constant/expression (0 - 65535) specifying the
amount of time to generate the tone(s). The unit of time for Duration
is described in Table 5.26.
• Freq1 is a variable/constant/expression (0 – 32767) specifying
frequency of the first tone. The unit of Freq1 is described in Table
5.26.
• Freq2 is an optional argument exactly like Freq1. When specified,
two frequencies will be mixed together on the specified I/O pin.
Quick Facts
Table 5.26: FREQOUT Quick
Facts.
BS2, BS2e
BS2sx
BS2p
BS2pe
BS2px
Units in
1 ms
0.4 ms
0.265 ms
1 ms
0.166 ms
Duration
Units in
1 Hz
2.5 Hz
3.77 Hz
1.51 Hz
6.03 Hz
Freq1 and
Freq2
Range of
0 to 32767 Hz 0 to 81917 Hz 0 to 123531 Hz 0 to 49478 Hz 0 to 197585 Hz
Frequency
Related
DTMFOUT and PWM
Commands
Explanation
FREQOUT generates one or two sine waves using a pulse-width
modulation algorithm. The circuits shown in Figure 5.6 will filter the
signal in order to play the tones through a speaker or audio amplifier.
Here’s a simple FREQOUT command:
SIMPLEST FORM OF FREQOUT.
FREQOUT 2, 1000, 2500
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 199
FREQOUT – BASIC Stamp Command Reference
On the BS2, this command generates a 2500 Hz tone for 1 second (1000 ms)
on I/O pin 2. See Table 5.26 for timing data on other BASIC Stamp
models.
To play two tones on the same I/O pin at once:
FREQOUT 2, 1000, 2500, 3000
GENERATING TWO TONES AT ONCE.
This will generate a 2500 Hz and 3000 Hz tone for 1 second. The
frequencies will mix together for a chord- or bell-like sound. To generate a
silent pause, specify frequency value(s) of 0.
Driving an Audio Amplifier
1k
1k
Amplifier
(e.g., Radio Shack
from I/O pin
0.1µF
0.01µF
Vss
Figure 5.6: Example RC filter
circuits for driving an audio
amplifier(top) or a speaker (bottom).
277-1008C)
Vss
Vss
Driving a Speaker
10µF (both)
from I/O pin
+
C1
+
C2
≥40Ω Speaker
(or 8Ω in series
with 33Ω resistor)
Vss
Vss
Notes:
C1 may be omitted for piezo speakers
C2 is optional, but reduces high-frequency noise
The circuits in Figure 5.6 work by filtering out the high-frequency PWM
used to generate the sine waves. FREQOUT works over a very wide range
of frequencies (as shown in Table 5.26) so at the upper end of its range,
those PWM filters will also filter out most of the desired frequency. You
may find it necessary to reduce values of the parallel capacitors shown in
the circuit, or to devise a custom active filter for your application.
Page 200 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
FREQUENCY CONSIDERATIONS.
5: BASIC Stamp Command Reference – FREQOUT
All
2
NOTE: This example program can be
used with all BS2 models. This program
uses conditional compilation techniques;
see Chapter 3 for more information.
Demo Program (FREQOUT.bs2)
'
'
'
'
FREQOUT.bs2
This program demonstrates sound-effects generation by the BASIC Stamp.
Conditional compilation sets timing and frequency adjustment factors so
that the output will sound the same on any BS2 model.
' {$STAMP BS2}
' {$PBASIC 2.5}
Spkr
PIN
#SELECT $STAMP
#CASE BS2, BS2E
TmAdj
CON
FrAdj
CON
#CASE BS2SX
TmAdj
CON
FrAdj
CON
#CASE BS2P
TmAdj
CON
FrAdj
CON
#CASE BS2PE
TmAdj
CON
FrAdj
CON
#CASE BS2PX
TmAdj
CON
FrAdj
CON
#ENDSELECT
10
' output pin for FREQOUT
$100
$100
' x 1.0 (time adjust)
' x 1.0 (freq adjust)
$280
$066
' x 2.5
' x 0.4
$3C5
$044
' x 3.77
' x 0.265
$100
$0A9
' x 1.0
' x 0.662
$607
$2A
' x 6.03
' x 0.166
Main:
DEBUG "Let's make a call...", CR
' combine 350 Hz & 440 Hz
FREQOUT Spkr, 2000 */ TmAdj, 350 */ FrAdj, 440 */ FrAdj
' dial number (digits 150 ms on, 25 ms off)
DTMFOUT Spkr, 150 */ TmAdj, 25, [5, 5, 5, 1, 2, 1, 2]
PAUSE 500
' bad connection (SIT sequence)
FREQOUT Spkr, 375 */ TmAdj, 985 */ FrAdj
FREQOUT Spkr, 375 */ TmAdj, 1371 */ FrAdj
FREQOUT Spkr, 375 */ TmAdj, 1777 */ FrAdj
DEBUG "Oops! -- try again...", CR
PAUSE 1000
DTMFOUT Spkr, 150 */ TmAdj, 25, [5, 5, 5, 2, 2, 2, 2]
DEBUG "Ringing"
FREQOUT Spkr, 2000 */ TmAdj, 440 */ FrAdj, 480 */ FrAdj
PAUSE 4000
FREQOUT Spkr, 2000 */ TmAdj, 440 */ FrAdj, 480 */ FrAdj
INPUT Spkr
END
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 201
FREQOUT – BASIC Stamp Command Reference
Page 202 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – GET
GET
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
GET Location, { WORD } Variable { , { WORD } Variable... }
NOTE: The optional arguments require
PBASIC 2.5.
Function
Read the value from Scratch Pad RAM (SPRAM) Location and store in
Variable.
• Location is a variable/constant/expression (0 – 63 for BS2e and
BS2sx and 0 – 131 for BS2p, BS2pe, and BS2px) that specifies the
SPRAM location to read from.
• Variable is a variable (usually a byte, or word if using the optional
WORD modifier) in which to store the value.
Quick Facts
Table 5.27: GET Quick Facts.
BS2e and BS2sx
Scratch Pad RAM
64 bytes (0 – 63). Organized as
Size and
bytes only.
Organization
General Purpose
0 - 62
Locations
Special Use
Location
BS2p, BS2pe, and BS2px
136 bytes (0 – 135). Organized as
bytes only.
0 – 126
Location 127: READ/WRITE slot and
Active Program slot (read only).
Locations 128-135: Polled Interrupt
status (read only).
PUT and STORE,
PUT
and SPSTR formatter.
Multiple sequential variables may be read from the Scratch Pad RAM.
The optional WORD modifier may be specified to retrieve 16-bit values.
Location 63: Active program slot
number (read only).
Related
Commands
PBASIC 2.5
Syntax Options
Explanation
The GET command reads a value from the specified Scratch Pad RAM
location and stores it into Variable. All values in all locations can be
retrieved from within any of the 8 program slots.
USES FOR SCRATCH PAD RAM.
SPRAM is useful for passing data to programs in other program slots and
for additional workspace. It is different than regular RAM in that symbol
names cannot be assigned directly to locations and each location is always
configured as a byte only. The following code will read the value at
location 25, store it in a variable called temp and display it:
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 203
GET – BASIC Stamp Command Reference
temp
VAR
Byte
GET 25, temp
DEBUG DEC temp
' retrieve byte from location 25
When using the PBASIC 2.5 directive, multiple sequential variables may
be read from the Scratch Pad RAM, starting at Location, and the WORD
modifier may be specified to retrieve 16-bit values.
' {$PBASIC 2.5}
temp
temp2
VAR
VAR
Byte
Word
GET 25, temp, Word temp2
' retrieve byte from location 25
' and word from locations 26 and 27
DEBUG DEC temp, CR
DEBUG DEC temp2
The low nibble of location 63 (BS2e and BS2sx) and location 127 (BS2p,
BS2pe, and BS2px) is a special, read-only location that always contains the
number of the currently running program slot. On the BS2p, BS2pe, and
BS2px, the high nibble of location 127 also contains the current program
slot that will be used for the READ and WRITE commands. See the demo
program below for an example of use.
Table 5.28 shows the layout of all SPRAM registers.
Page 204 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – GET
Table 5.28: Layout of SPRAM
Registers.
Location
0...62
64..126
BS2e and BS2sx
General Purpose RAM
Bits 0-3: Active program
slot number.
n/a
127
n/a
128
n/a
129
n/a
130
n/a
131
n/a
132
n/a
133
n/a
134
n/a
135
n/a
63
NOTE: Scratch Pad RAM can
only be accessed with the GET
and PUT commands. Scratch
Pad RAM cannot have variable
names assigned to it.
BS2p, BS2pe, and BS2px
General Purpose RAM
General Purpose RAM
General Purpose RAM
Bits 0-3, Active program slot #. Bits 4-7, program
slot for READ and WRITE operations.
Polled input trigger status of Main I/O pins 0-7
(0 = not triggered, 1 = triggered).
Polled input trigger status of Main I/O pins 8-15
(0 = not triggered, 1 = triggered).
Polled input trigger status of Auxiliary I/O pins
0-7 (0 = not triggered, 1 = triggered).
Polled input trigger status of Auxiliary I/O pins
8-15 (0 = not triggered, 1 = triggered).
Bits 0-3: Polled-interrupt mode, set by
POLLMODE
Bits 0-2: Polled-interrupt “run” slot, set by
POLLRUN.
Bit 0: Active I/O group; 0 = Main I/O,
1 = Auxiliary I/O.
Bit 0: Polled-output status (set by POLLMODE);
0 = disabled, 1= enabled.
Bit 1: Polled-input status; 0 = none defined,
1 = at least one defined.
Bit 2: Polled-run status (set by POLLMODE);
0 = disabled, 1 = enabled.
Bit 3: Polled-output latch status;
0 = real-time mode, 1 = latch mode.
Bit 4: Polled-input state;
0 = no trigger, 1 = triggered.
Bit 5: Polled-output latch state;
0 = nothing latched, 1 = signal latched.
Bit 6: Poll-wait state; 0 = No Event, 1 = Event
Occurred. (Cleared by POLLMODE only).
Bit 7: Polling status; 0 = not active, 1 = active.
Demo Program (GET_PUT1.bsx)
NOTE: This is written for the BS2sx but
can be used with the BS2e, BS2p,
BS2pe and BS2px also. This program
uses conditional compilation
techniques; see Chapter 3 for more
information.
'
'
'
'
'
'
'
GET_PUT1.bsx
This example demonstrates the use of the GET and PUT commands. First,
slot location is read using GET to display the currently running program
number. Then a set of values are written (PUT) into locations 0 TO 9.
Afterwards, program number 1 is RUN. This program is a BS2SX project
consisting of GET_PUT1.BSX and GET_PUT2.BSX, but will run on the BS2e,
BS2p, BS2pe and BS2px without modification.
' {$STAMP BS2sx, GET_PUT2.BSX}
' {$PBASIC 2.5}
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 205
GET – BASIC Stamp Command Reference
#SELECT $STAMP
#CASE BS2
#ERROR "BS2e or greater required."
#CASE BS2E, BS2SX
Slot
CON
63
#CASE BS2P, BS2PE, BS2PX
Slot
CON
127
#ENDSELECT
value
idx
VAR
VAR
Byte
Byte
Setup:
GET Slot, value
DEBUG "Program Slot #", DEC value.NIB0, CR
Main:
FOR idx = 0 TO 9
value = (idx + 3) * 8
PUT idx, value
DEBUG " Writing: ", DEC2 value, " to location: ", DEC2 idx, CR
NEXT
DEBUG CR
RUN 1
END
Demo Program (GET_PUT2.bsx)
'
'
'
'
'
'
'
GET_PUT2.bsx
This example demonstrates the use of the GET and PUT commands. First,
the Slot location is read using GET to display the currently running
program number. Then a set of values are read (GET) from locations
0 to 9 and displayed on the screen for verification. This program is a
BS2SX project consisting of GET_PUT1.BSX and GET_PUT2.BSX, but will run
on the BS2e, BS2p, BS2pe, and BS2px without modification.
' {$STAMP BS2sx}
' {$PBASIC 2.5}
#SELECT $STAMP
#CASE BS2
#ERROR "BS2e or greater required."
#CASE BS2E, BS2SX
Slot
CON
63
#CASE BS2P, BS2PE, BS2PX
Slot
CON
127
#ENDSELECT
value
idx
VAR
VAR
Byte
Byte
Page 206 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
NOTE: This is written for the BS2sx but
can be used with the BS2e, BS2p,
BS2pe and BS2px also. This program
uses conditional compilation
techniques; see Chapter 3 for more
information.
5: BASIC Stamp Command Reference – GET
Setup:
GET Slot, value
DEBUG "Program Slot #", DEC value.NIB0, CR
Main:
FOR idx = 0 TO 9
GET idx, value
DEBUG " Reading: ", DEC2 value, " from location: ", DEC2 idx, CR
NEXT
END
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 207
GET – BASIC Stamp Command Reference
Page 208 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – GOSUB
GOSUB
1 All 2
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
GOSUB Address
Function
Store the address of the next instruction after GOSUB, then go to the point
in the program specified by Address; with the intention of returning to the
stored address.
• Address is a label that specifies where to go.
Quick Facts
Table 5.29: GOSUB Quick Facts.
Max. GOSUBs
per program
Max. nested
GOSUBs
Related
Commands
BS1
All BS2 Models
16
255
4
4
GOTO
ON...GOSUB and GOTO
Explanation
GOSUB is a close relative of GOTO, in fact, its name means, "GO to a
SUBroutine". When a PBASIC program reaches a GOSUB, the program
executes the code beginning at the specified address label. Unlike GOTO,
GOSUB also stores the address of the instruction immediately following
itself. When the program encounters a RETURN command, it interprets it
to mean, “go to the instruction that follows the most recent GOSUB.” In
other words, a GOSUB makes the BASIC Stamp do a similar operation as
you do when you see a table or figure reference in this manual; 1) you
remember where you are, 2) you go to the table or figure and read the
information there, and 3) when you've reached the end of it, you "return"
to the place you were reading originally.
GOSUB CAN SAVE EEPROM
(PROGRAM) SPACE.
GOSUB is mainly used to execute the same piece of code from multiple
locations. If you have, for example, a block of three lines of code that need
to be run from 10 different locations in your entire program you could
simply copy and paste those three lines to each of those 10 locations. This
would amount to a total of 30 lines of repetitive code (and extra space
wasted in the program memory). A better solution is to place those three
lines in a separate routine, complete with it's own label and followed by a
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 209
GOSUB – BASIC Stamp Command Reference
RETURN command, then just use a GOSUB command at each of the 10
locations to access it. This technique can save a lot of program space.
Try the example below:
Main:
GOSUB Hello
DEBUG "How are you?"
END
Hello:
DEBUG "Hello, my friend!", CR
RETURN
The above code will start out by GOSUB'ing to the section of code
beginning with the label Hello. It will print "Hello, my friend!" on the
screen then RETURN to the line after the GOSUB… which prints "How are
you?" and ENDs. Note: colons ( : ) are placed after labels, as in “ “Main: “
and “Hello:” but the colon is not used on references to these labels such as
in the “GOSUB Hello” line.
There's another interesting lesson here; what would happen if we removed
the END command from this example? Since the BASIC Stamp reads the
code from left to right / top to bottom (like the English language) once it
had returned to and run the "How are you?" line, it would naturally "fall
into" the Hello routine again. Additionally, at the end of the Hello routine,
it would see the RETURN again (although it didn't GOSUB to that routine
this time) and because there wasn't a previous place to return to, the
BASIC Stamp will start the entire program over again. This would cause
an endless loop. The important thing to remember here is to always make
sure your program doesn't allow itself to "fall into" a subroutine.
A limited number of GOSUBs are allowed per program (as shown in Table
5.29), and they may be nested only four levels deep. In other words, the
subroutine that’s the destination of a GOSUB can contain a GOSUB to
another subroutine, and so on, to a maximum depth (total number of
GOSUBS before the first RETURN) of four. Any deeper, and the program
will "forget" its way back to the starting point (the instruction following
the very first GOSUB).
When GOSUBS are nested, each RETURN takes the program back to the
instruction after the most-recent GOSUB. As is mentioned above, if the
Page 210 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
WATCH OUT FOR SUBROUTINES THAT
YOUR PROGRAM CAN "FALL INTO."
1
NOTE: On the BS1, a RETURN
without a GOSUB will return the
program to the last GOSUB (or will end
the program if no GOSUB was
executed).
GOSUB LIMITATIONS.
5: BASIC Stamp Command Reference – GOSUB
BASIC Stamp encounters a RETURN without a previous GOSUB, the
entire program starts over from the beginning. Take care to avoid these
phenomena.
1
Demo Program (GOSUB.bs1)
'
'
'
'
'
'
'
'
'
'
GOSUB.bs1
This program is a guessing game that generates a random number in a
subroutine called Pick_A_Number. It is written to stop after ten
guesses. To see a common bug associated with GOSUB, delete or comment
out the line beginning with END after the FOR-NEXT loop. This means
that after the loop is finished, the program will wander into the
Pick_A_Number subroutine. When the RETURN at the end executes, the
program will go back to the beginning of the program. This will cause
the program to execute endlessly. Make sure that your programs can't
accidentally execute subroutines!
' {$STAMP BS1}
' {$PBASIC 1.0}
SYMBOL
SYMBOL
SYMBOL
rounds
numGen
myNum
= B2
= W0
= B3
Setup:
numGen = 11500
' number of reps
' random number holder
' random number, 1-10
' initialize random "seed"
Main:
FOR rounds = 1 TO 10
DEBUG CLS, "Pick a number from 1 to 10", CR
GOSUB Pick_A_Number
PAUSE 2000
' dramatic pause
DEBUG "My number was: ", #myNum
' show the number
PAUSE 1000
' another pause.
NEXT
DEBUG CLS, "Done"
END
' end program
'
'
'
'
Random-number subroutine.
the RETURN instruction at
subroutines with a GOSUB.
correct address, and your
A subroutine is just a piece of code with
the end. Always make sure your program enters
If you don't, the RETURN won't have the
program will have a bug!
Pick_A_Number:
RANDOM numGen
DEBUG numGen, CR
myNum = numGen / 6550 MIN 1
RETURN
' stir up the bits of NumGen.
' scale to fit 1-10 range.
' go back to 1st instruction
' after GOSUB that got us here
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 211
GOSUB – BASIC Stamp Command Reference
Demo Program (GOSUB.bs2)
'
'
'
'
'
'
'
'
'
'
All
GOSUB.bs2
This program is a guessing game that generates a random number in a
subroutine called Pick_A_Number. It is written to stop after ten
guesses. To see a common bug associated with GOSUB, delete or comment
out the line beginning with END after the FOR-NEXT loop. This means
that after the loop is finished, the program will wander into the
Pick_A_Number subroutine. When the RETURN at the end executes, the
program will go back to the beginning of the program. This will cause
the program to execute endlessly. Make sure that your programs can't
accidentally execute subroutines!
' {$STAMP BS2}
' {$PBASIC 2.5}
rounds
numGen
myNum
VAR
VAR
VAR
Byte
Word
Byte
Setup:
numGen = 11500
' initialize random "seed"
Main:
FOR rounds = 1 TO 10
DEBUG CLS, "Pick a number from 1 to
GOSUB Pick_A_Number
PAUSE 2000
DEBUG "My number was: ", DEC myNum
PAUSE 1000
NEXT
DEBUG CLS, "Done"
END
'
'
'
'
Random-number subroutine.
the RETURN instruction at
subroutines with a GOSUB.
correct address, and your
' number of reps
' random number holder
' random number, 1-10
10", CR
' dramatic pause
' show the number
' another pause.
' end program
A subroutine is just a piece of code with
the end. Always make sure your program enters
If you don't, the RETURN won't have the
program will have a bug!
Pick_A_Number:
RANDOM numGen
DEBUG DEC ? numGen
myNum = numGen / 6550 MIN 1
RETURN
' stir up the bits of NumGen.
' scale to fit 1-10 range.
' go back to 1st instruction
' after GOSUB that got us here
Page 212 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
2
NOTE: This example program can be
used with all BS2 models by changing
the $STAMP directive accordingly.
5: BASIC Stamp Command Reference – GOTO
GOTO
1 All 2
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
GOTO Address
Function
Go to the point in the program specified by Address.
• Address is a label that specifies where to go.
Quick Facts
Table 5.30: GOTO Quick Facts.
Related
Commands
Max. GOTOs
per Program
BS1
All BS2 Models
BRANCH and GOSUB
ON...GOTO, BRANCH and GOSUB
Unlimited, but good programming practices
suggest using the least amount possible.
Explanation
The GOTO command makes the BASIC Stamp execute the code that starts
at the specified Address location. The BASIC Stamp reads PBASIC code
from left to right / top to bottom, just like in the English language. The
GOTO command forces the BASIC Stamp to jump to another section of
code.
A common use for GOTO is to create endless loops; programs that repeat a
group of instructions over and over. For example:
Start:
DEBUG "Hi", CR
GOTO Start
The above code will print "Hi" on the screen, over and over again. The
GOTO Start line simply tells it to go back to the code that begins with the
label Start. Note: colons ( : ) are placed after labels, as in “Start:” to further
indicate that they are labels, but the colon is not used on references to
labels such as in the “GOTO Start” line.
1 All 2
NOTE: This is written for the BS2 but
can be used for the BS1 and all other
BS2 models as well, by modifying the
$STAMP directive accordingly.
Demo Program (GOTO.bs2)
'
'
'
'
'
GOTO.bs2
This program is not very practical, but demonstrates the use of GOTO to
jump around the code. This code jumps between three different routines,
each of which print something different on the screen. The routines are
out of order for this example.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 213
GOTO – BASIC Stamp Command Reference
'{$STAMP
BS2}
GOTO Routine1
Routine2:
DEBUG "We're in routine #2",CR
PAUSE 1000
GOTO Routine3
Routine1:
DEBUG "We're in routine #1",CR
PAUSE 1000
GOTO Routine2
Routine3:
DEBUG "We're in routine #3",CR
PAUSE 1000
GOTO Routine1
Page 214 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – HIGH
HIGH
1 All 2
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px BS2px
HIGH Pin
Function
1
NOTE: Expressions are not allowed as
arguments on the BS1. The range of
the Pin argument on the BS1 is 0 – 7.
Make the specified pin output high.
• Pin is a variable/constant/expression (0 – 15) that specifies which
I/O pin to set high. This pin will be placed into output mode.
Quick Facts
Table 5.31: HIGH Quick Facts.
BS1 and all BS2 Models
Related
Commands
LOW and TOGGLE
Explanation
The HIGH command sets the specified pin to 1 (a +5 volt level) and then
sets its mode to output. For example,
HIGH 6
does exactly the same thing as:
All
2
OUT6 = 1
DIR6 = 1
Using the HIGH command is faster and more concise, in this case.
Connect an LED and a resistor as shown in Figure 5.7 for demo program
HIGH.bs2, below.
Figure 5.7: Example LED Circuit.
P0
LED
470 Ω
Vss
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 215
HIGH – BASIC Stamp Command Reference
Demo Program (HIGH.bs2)
'
'
'
'
HIGH.bs2
This simple program sets I/O pin 0 high for 1/2 second and low for
1/2 second in an endless loop. Connect an LED to P0 for a simple
blinker.
' {$STAMP BS2}
Main:
HIGH 0
PAUSE 500
LOW 0
PAUSE 500
GOTO Main
END
Page 216 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
1 All 2
NOTE: This is written for the BS2 but
can be used for the BS1 and all other
BS2 models as well, by modifying the
$STAMP directive accordingly.
5: BASIC Stamp Command Reference – I2CIN
I2CIN
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
I2CIN Pin, SlaveID, { Address { \LowAddress }, } [ InputData ]
Function
Receive data from a device using the I2C protocol.
• Pin is a variable/constant/expression (0 or 8) that specifies which
I/O pins to use. I2C devices require two I/O pins to communicate.
The Pin argument serves a double purpose; specifying the first pin
(for connection to the chip's SDA pin) and, indirectly, the other
required pin (for connection to the chip's SCL pin). See explanation
below. Both I/O pins will be toggled between output and input
mode during the I2CIN command and both will be set to input
mode by the end of the I2CIN command.
• SlaveID is a variable/constant/expression (0 – 255) indicating the
unique ID of the I2C chip.
• Address is an optional variable/constant/expression (0 – 255)
indicating the desired address within the I2C chip to receive data
from. The Address argument may be used with the optional
LowAddress argument to indicate a word-sized address value.
• LowAddress is an optional variable/constant/expression (0 – 255)
indicating the low-byte of the word-sized address within the I2C
chip to receive data from. This argument must be used along with
the Address argument.
• InputData is a list of variables and modifiers that tells I2CIN what to
do with incoming data. I2CIN can store data in a variable or array,
interpret numeric text (decimal, binary, or hex) and store the
corresponding value in a variable, wait for a fixed or variable
sequence of bytes, or ignore a specified number of bytes. These
actions can be combined in any order in the InputData list.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 217
I2CIN – BASIC Stamp Command Reference
Quick Facts
Values for Pin
I/O Pin
Arrangement
Transmission
Rate
Special Notes
BS2p, BS2pe, and BS2px
Pin = 0
Pin = 8
0: Serial Data (SDA) pin
8: Serial Data (SDA) pin
1: Serial Clock (SCL) pin
9: Serial Clock (SCL) pin
Approximately 81 kbits/sec on a BS2p, 45 kbits/sec on a BS2pe, and 83
kbits/sec on a BS2px (not including overhead).
Both the SDA and SCL pins must have 1 kΩ - 4.7 kΩ pull-up resistors.
The I2CIN command does not allow for multiple masters.
2
The BASIC Stamp cannot operate as an I C slave device.
Related
Command
Table 5.32: I2CIN Quick Facts.
I2COUT
Explanation
The I2C protocol is a form of synchronous serial communication developed
by Phillips Semiconductors. It only requires two I/O pins and both pins
can be shared between multiple I2C devices. The I2CIN command allows
the BASIC Stamp to receive data from an I2C device.
The following is an example of the I2CIN command:
A SIMPLE I2CIN EXAMPLE.
result VAR
Byte
I2CIN 0, $A1, 0, [result]
This code will transmit a "read" command to an I2C device (connected to
I/O pins 0 and 1) and then will receive one byte and store it in the variable
result. Though it may seem strange, the I2CIN command first transmits
some data and then receives data. It must first transmit information (ID,
read/write and address) in order to tell the I2C device what information it
would like to receive. The exact information transmitted ($A1, 0) depends
on the I2C device that is being used.
The above example will read a byte of data from location 0 of a 24LC16B
EEPROM from Microchip. Figure 5.8 shows the proper wiring for this
example to work. The SlaveID argument ($A1) is both the ID of the chip
and the command to read from the chip; the 1 means read. The Address
argument (0) is the EEPROM location to read from.
Page 218 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
NOTE: The I2C command will make up
to 8 attempts to connect to the
addressed device. If the device does
not properly respond, the I2C command
will timeout and the InputData will
remain unchanged..
5: BASIC Stamp Command Reference – I2CIN
Figure 5.8: Example Circuit for the
I2CIN command and a 24LC16B
EEPROM.
P0
SDA
P1
SCL
Vdd
Note: The 4.7 kΩ
resistors are required for the
I2CIN command to function
properly.
4.7 kΩ
1
2
3
4
Vss
RECEIVING FORMATTED DATA.
8
7
6
5
4.7 kΩ
24LC16B
(DIP)
The I2CIN command's InputData argument is similar to the SERIN
command's InputData argument. This means data can be received as
ASCII character values, decimal, hexadecimal and binary translations and
string data as in the examples below. (Assume the 24LC16B EEPROM is
used and it has the string, "Value: 3A:101" stored, starting at location 0).
value
I2CIN
I2CIN
I2CIN
I2CIN
I2CIN
VAR
0,
0,
0,
0,
0,
$A1,
$A1,
$A1,
$A1,
$A1,
Byte(13)
0,
0,
0,
0,
0,
[value]
[DEC value]
[HEX value]
[BIN value]
[STR value\13]
'
'
'
'
'
receive
receive
receive
receive
receive
the
the
the
the
the
ASCII value for "V"
number 3
number $3A
number %101
string "Value: 3A:101"
Table 5.33 and Table 5.34 below list all the available special formatters and
conversion formatters available to the I2CIN command. See the SERIN
command for additional information and examples of their use.
Table 5.33: I2CIN Special
Formatters.
Special Formatter
SKIP Length
SPSTR L
STR ByteArray \L {\E}
WAITSTR ByteArray {\L}
Action
Ignore Length bytes of characters.
Input a character stream of length L bytes (up to 126) into
Scratch Pad RAM, starting at location 0. Use GET to retrieve
the characters.
Input a character string of length L into an array. If specified,
an end character E causes the string input to end before
reaching length L. Remaining bytes are filled with 0s (zeros).
Wait for a sequence of bytes matching a string stored in an
array variable, optionally limited to L characters. If the
optional L argument is left off, the end of the array-string must
be marked by a byte containing a zero (0).
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 219
I2CIN – BASIC Stamp Command Reference
Conversion
Formatter
Type of Number
DEC{1..5}
SDEC{1..5}
Decimal, optionally limited to 1 – 5 digits
Signed decimal, optionally limited to 1 – 5
digits
Hexadecimal, optionally limited to 1 – 4 digits
HEX{1..4}
SHEX{1..4}
IHEX{1..4}
ISHEX{1..4}
BIN{1..16}
SBIN{1..16}
IBIN{1..16}
ISBIN{1..16}
NUM
2
3
4
5
Notes
1
1,2
0 through 9, A
through F
-, 0 through 9,
A through F
$, 0 through 9,
A through F
-, $, 0 through
9, A through F
0, 1
-, 0, 1
1,3,5
1
1,2
%, 0, 1
1,4
-, %, 0, 1
1,2,4
$, %, 0 through
9, A through F
1, 3, 4
1,2,3
1,3,4
1,2,3,4
-, $, %,
0 through 9,
1,2,3,4
A through F
All numeric conversions will continue to accept new data until receiving either the specified
number of digits (ex: three digits for DEC3) or a non-numeric character.
To be recognized as part of a number, the minus sign (-) must immediately precede a
numeric character. The minus sign character occurring in non-numeric text is ignored and
any character (including a space) between a minus and a number causes the minus to be
ignored.
The hexadecimal formatters are not case-sensitive; “a” through “f” means the same as “A”
through “F”.
Indicated hexadecimal and binary formatters ignore all characters, even valid numerics,
until they receive the appropriate prefix ($ for hexadecimal, % for binary). The indicated
formatters can differentiate between text and hexadecimal (ex: ABC would be interpreted
by HEX as a number but IHEX would ignore it unless expressed as $ABC). Likewise, the
binary version can distinguish the decimal number 10 from the binary number %10. A
prefix occurring in non-numeric text is ignored, and any character (including a space)
between a prefix and a number causes the prefix to be ignored. Indicated, signed
formatters require that the minus sign come before the prefix, as in -$1B45.
The HEX modifier can be used for Decimal to BCD Conversion. See “Hex to BCD
Conversion” on page 97.
SNUM
1
Signed hexadecimal, optionally limited to
1 – 4 digits
Indicated hexadecimal, optionally limited to
1 – 4 digits
Signed, indicated hexadecimal, optionally
limited to 1 – 4 digits
Binary, optionally limited to 1 – 16 digits
Signed binary, optionally limited to 1 – 16
digits
Indicated binary, optionally limited to 1 – 16
digits
Signed, indicated binary, optionally limited to
1 – 16 digits
Generic numeric input (decimal, hexadecimal
or binary); hexadecimal or binary number
must be indicated
Numeric
Characters
Accepted
0 through 9
-, 0 through 9
Similar to NUM with value treated as signed
with range -32768 to +32767
For examples of all conversion formatters and how they process incoming
data, see Appendix C.
Page 220 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 5.34: I2CIN Conversion
Formatters.
5: BASIC Stamp Command Reference – I2CIN
2
THE I C PROTOCOL FORMAT.
Figure 5.9: Slave ID Format.
The I2C protocol has a well-defined standard for the information passed at
the start of each transmission. First of all, any information sent must be
transmitted in units of 1 byte (8-bits). The first byte, we call the SlaveID, is
an 8-bit pattern whose upper 7-bits contain the unique ID of the device
you wish to communicate with. The lowest bit indicates whether this is a
write operation (0) or a read operation (1). Figure 5.9 shows this format.
7
6
5
4
3
2
1
0
A6
A5
A4
A3
A2
A1
A0 R/W
The second byte, immediately following the SlaveID, is the optional
Address. It indicates the 8-bit address (within the device) containing the
data you would like to receive. Note that the Address argument is optional
and may be left unspecified for devices that don't require an Address
argument.
USING LONG ADDRESSES.
Some devices require more than 8 bits of address. For this case, the
optional LowAddress argument can be used for the low-byte of the required
address. When using the LowAddress argument, the Address argument is
effectively the high-byte of the address value. For example, if the entire
address value is 2050, use 8 for the Address argument and 2 for the
LowAddress argument (8 * 256 + 2 = 2050).
Following the last address byte is the first byte of data. This data byte may
be transmitted or received by the BASIC Stamp. In the case of the I2CIN
command, this data byte is transmitted by the device and received by the
BASIC Stamp. Additionally, multiple data bytes can follow the address,
depending on the I2C device. Note that every device has different
limitations regarding how may contiguous bytes they can receive or
transmit in one session. Be aware of these device limitations and program
accordingly.
START AND STOP CONDITIONS AND
ACKNOWLEDGMENTS.
Every I2C transmission session begins with a Start Condition and ends
with a Stop Condition. Additionally, immediately after every byte is
transmitted, an extra clock cycle is used to send or receive an
acknowledgment signal (ACK). All of these operations are automatically
taken care of by the I2CIN command so that you need not be concerned
with them. The general I2C transmission format is shown in Figure 5.10.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 221
I2CIN – BASIC Stamp Command Reference
S
T
A
R
T
B
U
S
SlaveID
S a6 a5 a4 a3 a2 a1 a0 rw
A
C
K
Data
S F
A T R
C O E
K P E
d7 d6 d5 d4 d3 d2 d1 d0
P
A
C
K
Address
a7 a6 a5 a4 a3 a2 a1 a0
2
Figure 5.10: I C Transmission
Format.
NOTES:
S = Start Condition
P = Stop Condition
a = id or address bit
2
d = data bit (transmitted by the BASIC Stamp or the I C device)
ACK = Acknowledge signal. (Most acknowledge signals are generated by the I2C device)
Since the I2CIN command is intended for input only, it actually overrides
the "R/W" bit (bit 0) in the SlaveID argument. This is done so that it can
use the I2C protocol's "Combined Format" for receiving data. Put simply,
this means a command such as: I2CIN 0, $A1, 10, [Result] actually
transmits $A0, then 10, then $A1 and then it reads the data back from the
device. The $A0 means "write", the 10 is the address to write to, and
finally, the $A1 indicates a change of direction; to "read" the location,
instead. Even though the I2CIN command really doesn't care what the
value of the SlaveID's LSB is, it is suggested that you still set it
appropriately for clarity.
SPECIAL NOTE ABOUT I2CIN
INPLIMENTATION.
Also note that the I2CIN command does not support multiple I2C masters
and the BASIC Stamp cannot operate as an I2C slave device.
Demo Program (I2C.bsp)
'
'
'
'
'
I2C.bsp
This program demonstrates writing and reading every location in a 24LC16B
EEPROM using the BS2p/BS2pe's I2C commands. Connect the BS2p, BS2pe, or
BS2px to the 24LC16B DIP EEPROM as shown in the diagram in the I2CIN or
I2COUT command description.
' {$STAMP BS2p}
' {$PBASIC 2.5}
#IF ($STAMP < BS2P) #THEN
#ERROR "Program requires BS2p, BS2pe, or BS2px."
#ENDIF
SDA
SCL
PIN
PIN
0
SDA + 1
' I2C SDA pin
Page 222 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
NOTE: This example program can be
used with the BS2p, BS2pe, and
BS2px. This program uses conditional
compilation techniques; see Chapter 3
for more information.
5: BASIC Stamp Command Reference – I2CIN
addr
block
value
check
result
VAR
VAR
VAR
VAR
VAR
Word
Nib
Byte
Nib
Byte(16)
'
'
'
'
'
internal address
block address in 24LC16
value to write
for checking retuned values
array for returned value
Write_To_EEPROM:
DEBUG "Writing...", CR
PAUSE 2000
FOR addr = 0 TO 2047 STEP 16
' loop through all addresses
block = addr.NIB2
<
>=
4000) THEN
DEBUG "Value was greater than 4000"
ELSEIF (value = 4000) THEN
DEBUG "Value was equal to 4000"
ELSE
DEBUG "Value was less than 4000"
ENDIF
' evaluate duration
This IF…THEN construct does the same thing as in the previous example:
1) if value is greater than 4000:
it displays “Value was greater than 4000”
2) else, if value is equal to 4000 (the ELSEIF part):
it displays “Value was equal to 4000”
3) and finally (ELSE) if none of the above were true:
it displays “Value was less than 4000”
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 239
IF…THEN – BASIC Stamp Command Reference
Note that an IF…THEN construct can have as many as sixteen (16) ELSEIF
clauses, but a maximum of only one (1) ELSE clause.
There are three demo programs below. The first two demonstrate the
PBASIC 1.0 (BS1) and PBASIC 2.0 (all BS2 models) form of the IF…THEN
command. The last example demonstrates the PBASIC 2.5 (all BS2
models) form of IF…THEN.
Demo Program (IF-THEN.bs1)
'
'
'
'
'
'
1
IF-THEN.bs1
The program below generates a series of 16-bit random numbers and tests
each to determine whether they're evenly divisible by 3. If a number is
evenly divisible by 3, then it is printed, otherwise, the program
generates another random number. The program counts how many numbers it
prints, and quits when this number reaches 10.
' {$STAMP BS1}
' {$PBASIC 1.0}
SYMBOL
SYMBOL
SYMBOL
sample
samps
temp
= W0
= B2
= B3
' Random number to be tested
' Number of samples taken
' Temporary workspace
Setup:
sample = 11500
Mult3:
RANDOM sample
temp = sample // 3
IF temp 0 THEN Mult3
DEBUG #sample, "divides by 3", CR
samps = samps + 1
IF samps = 10 THEN Done
GOTO Mult3
' Put a random number into sample
'
'
'
'
'
Not multiple of 3? -- try again
show sample divisible by 3
Count multiples of 3
Quit with 10 samples
keep checking
Done:
DEBUG CR, "All done."
END
Demo Program (IF-THEN.bs2)
'
'
'
'
'
'
IF-THEN.bs2
The program below generates a series of 16-bit random numbers and tests
each to determine whether they're evenly divisible by 3. If a number is
evenly divisible by 3, then it is printed, otherwise, the program
generates another random number. The program counts how many numbers it
prints, and quits when this number reaches 10.
Page 240 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
All
2
NOTE: This example program can be
used with all BS2 models by changing
the $STAMP directive accordingly.
5: BASIC Stamp Command Reference – IF...THEN
' {$STAMP BS2}
' {$PBASIC 2.0}
sample
samps
temp
VAR
VAR
VAR
Word
Nib
Nib
' Random number to be tested
' Number of samples taken
' Temporary workspace
Setup:
sample = 11500
Mult3:
RANDOM sample
' Put a random number into sample
temp = sample // 3
IF temp 0 THEN Mult3
' Not multiple of 3? -- try again
DEBUG DEC5 sample, " divides by 3", CR
samps = samps + 1
' Count multiples of 3
IF samps = 10 THEN Done
' Quit with 10 samples
GOTO Mult3
' keep checking
Done:
DEBUG CR, "All done."
END
All
2
NOTE: This example program can be
used with all BS2 models by changing
the $STAMP directive accordingly.
Demo Program (IF-THEN-ELSE.bs2)
'
'
'
'
'
'
IF-THEN-ELSE.bs2
The program below generates a series of 16-bit random numbers and tests
each to determine whether they're evenly divisible by 3. If a number is
evenly divisible by 3, then it is printed, otherwise, the program
generates another random number. The program counts how many numbers it
prints, and quits when this number reaches 10.
' {$STAMP BS2}
' {$PBASIC 2.5}
sample
hits
misses
' version 2.5 required
VAR
VAR
VAR
Word
Nib
Word
' Random number to be tested
' Number of hits
' Number of misses
Setup:
sample = 11500
Main:
DO
RANDOM sample
IF ((sample // 3) = 0) THEN
DEBUG DEC5 sample,
" is divisible by 3", CR
' Put a random number into sample
' divisible by 3?
' - yes, print value and message
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 241
IF…THEN – BASIC Stamp Command Reference
hits = hits + 1
ELSE
misses = misses + 1
ENDIF
LOOP UNTIL (hits = 10)
DEBUG CR,
"All done.",
"Hits:
",
"Misses: ",
"Samples: ",
END
CR,
DEC
DEC
DEC
' count hits (divisible by 3)
' count misses
' quit after 10 hits
CR,
' display results
hits, CR,
misses, CR,
(hits + misses)
Page 242 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – INPUT
INPUT
1 All 2
1
NOTE: Expressions are not allowed as
arguments on the BS1. The range of
the PIN argument on the BS1 is 0 – 7.
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
INPUT Pin
Function
Make the specified pin an input.
• Pin is a variable/constant/expression (0 – 15) that specifies which
I/O pin to set to input mode.
Quick Facts
Table 5.41: INPUT Quick Facts.
Input Pin
Variables
Related
Commands
BS1
All BS2 Models
PINS; PIN0 through PIN7
INS; IN0 through IN15
OUTPUT and REVERSE
Explanation
There are several ways to make a pin an input. When a program begins,
all of the BASIC Stamp's pins are inputs. Commands that rely on input
pins, like PULSIN and SERIN, automatically change the specified pin to
input. Writing 0s to particular bits of the variable DIRS makes the
corresponding pins inputs. And then there’s the INPUT command.
When a pin is an input, your program can check its state by reading the
corresponding INS variable (PINS on the BS1). For example:
All
2
INPUT 4
Hold:
IF IN4 = 0 THEN Hold
' stay here until P4 = 1
The code above will read the state of P4 as set by external circuitry. If
nothing is connected to P4, it will alternate between states (1 or 0)
apparently at random.
What happens if your program writes to the OUTS bit (PINS bit on the
BS1) of a pin that is set up as an input? The value is stored in OUTS (PINS
on the BS1), but has no effect on the outside world. If the pin is changed to
output, the last value written to the corresponding OUTS bit (or PINS bit
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 243
INPUT – BASIC Stamp Command Reference
on the BS1) will appear on the pin. The demo program shows how this
works.
Demo Program (INPUT.bs1)
'
'
'
'
'
'
'
'
'
'
1
INPUT.bs1
This program demonstrates how the input/output direction of a pin is
determined by the corresponding bit of DIRS. It also shows that the
state of the pin itself (as reflected by the corresponding bit of PINS)
is determined by the outside world when the pin is an input, and by the
corresponding bit of OUTS when it's an output. To set up the demo,
connect a 10k resistor from +5V to P7 on the BASIC Stamp. The resistor
to +5V puts a high (1) on the pin when it's an input. The BASIC Stamp
can override this state by writing a low (0) to bit 7 of OUTS and
changing the pin to output.
' {$STAMP BS1}
' {$PBASIC 1.0}
Main:
INPUT 7
DEBUG "State of P7: ", #PIN7, CR
' Make P7 an input
PIN7 = 0
DEBUG "After 0 written to OUT7: "
DEBUG #PIN7, CR
' Write 0 to output latch
OUTPUT 7
DEBUG "After P7 changed to output: "
DEBUG #PIN7
' Make P7 an output
Demo Program (INPUT.bs2)
'
'
'
'
'
'
'
'
'
'
All
INPUT.bs2
This program demonstrates how the input/output direction of a pin is
determined by the corresponding bit of DIRS. It also shows that the
state of the pin itself (as reflected by the corresponding bit of INS)
is determined by the outside world when the pin is an input, and by the
corresponding bit of OUTS when it's an output. To set up the demo,
connect a 10k resistor from +5V to P7 on the BASIC Stamp. The resistor
to +5V puts a high (1) on the pin when it's an input. The BASIC Stamp
can override this state by writing a low (0) to bit 7 of OUTS and
changing the pin to output.
' {$STAMP BS2}
' {$PBASIC 2.5}
Main:
INPUT 7
DEBUG "State of P7: ",
' Make P7 an input
Page 244 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
2
NOTE: This example program can be
used with all BS2 models by changing
the $STAMP directive accordingly.
5: BASIC Stamp Command Reference – INPUT
BIN1 IN7, CR
OUT7 = 0
DEBUG "After 0 written to OUT7: ",
BIN1 IN7, CR
' Write 0 to output latch
OUTPUT 7
' Make P7 an output
DEBUG "After P7 changed to output: ",
BIN1 IN7
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 245
INPUT – BASIC Stamp Command Reference
Page 246 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – IOTERM
IOTERM
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
IOTERM Port
Function
Switch control to main I/O pins or auxiliary I/O pins (on the BS2p40 only)
depending on state of Port.
• Port is a variable/constant/expression (0 – 1) that specifies which
I/O port to use.
Quick Facts
Table 5.42: IOTERM Quick Facts.
Values for Port
I/O pin IDs
Special Notes
Related
Commands
BS2p, BS2pe, and BS2px
0 = switch to main I/O group, 1 = switch to auxiliary I/O group.
0 – 15 (after IOTERM command, all references affect physical pins 5 –
20 or 21 – 36 depending on state of Port).
Both the BS2p and BS2pe 24-pin modules accept this command,
however, only the BS2p40 gives access to the auxiliary I/O pins.
AUXIO and MAINIO
Explanation
The BS2p, BS2pe and BS2px are available as 24-pin modules that are pin
compatible with the BS2, BS2e and BS2sx. Also available is a 40-pin
module called the BS2p40, with an additional 16 I/O pins (for a total of
32). The BS2p40's I/O pins are organized into two groups, called main
and auxiliary. The I/O pins in each group can be accessed in the same
manner (by referencing I/O pins 0 – 15) but access is only possible within
one group at a time. The IOTERM command causes the BASIC Stamp to
affect either the main or auxiliary I/O pins in all further code until the
MAINIO, AUXIO or another IOTERM command is reached, or the BASIC
Stamp is reset or power-cycled. The value of Port determines which group
of I/O pins will be referenced. Using 0 for Port will switch to the main
I/O group and using 1 for Port will switch to the auxiliary group.
A SIMPLE IOTERM EXAMPLE.
The following example illustrates this:
HIGH 0
IOTERM 1
LOW 0
' make P0 high
' Port = 1, so switch to auxiliary pins
' make X0 low
The first line of the above example will set I/O pin 0 of the main I/O pins
(physical pin 5) high. Afterward, the IOTERM command tells the BASIC
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 247
IOTERM – BASIC Stamp Command Reference
Stamp that all commands following it should affect the auxiliary I/O pins
(Port = 1). The following LOW command will set I/O pin 0 of the
auxiliary I/O pins (physical pin 21) low.
Note that the main I/O and auxiliary I/O pins are independent of each
other; the states of the main I/O pins remain unchanged while the
program affects the auxiliary I/O pins, and vice versa.
MAIN I/O AND AUXILIARY I/O PINS ARE
INDEPENDENT AND UNAFFECTED BY
CHANGES IN THE OPPOSITE GROUP.
Other commands that affect I/O group access are AUXIO and MAINIO.
2
Demo Program (AUX_MAIN_TERM.bsp)
p
' AUX_MAIN_TERM.bsp
' This program demonstrates the use of the AUXIO, MAINIO and IOTERM
' commands to affect I/O pins in the auxiliary and main I/O groups.
' {$STAMP BS2p}
' {$PBASIC 2.5}
#SELECT $STAMP
#CASE BS2, BS2E, BS2SX
#ERROR "Program requires BS2p40"
#CASE BS2P, BS2PE, BS2PX
DEBUG "Note: This program designed for the BS2p40.", CR
#ENDSELECT
port
VAR
Main:
DO
MAINIO
TOGGLE 0
PWM 1, 100, 40
Bit
' Switch to main I/O pins
' Toggle state of I/O pin P0
' Generate PWM on I/O pin P1
AUXIO
TOGGLE 0
PULSOUT 1, 1000
PWM 2, 100, 40
'
'
'
'
Switch to auxiliary
Toggle state of I/O
Generate a pulse on
Generate PWM on I/O
IOTERM port
'
'
'
'
'
'
Switch to main or aux I/Os
-- depending on port
Toggle state of I/O pin 3
-- on main and aux, alternately
Invert port
1 second delay
TOGGLE 3
port = ~port
PAUSE 1000
LOOP
END
Page 248 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
I/O
pin
I/O
pin
pins
X0
pin X1
X2
NOTE: This example program will
tokenize with the 24-pin BS2p, BS2pe,
and BS2px but its effects can only be
seen on the BS2p40. This program
uses conditional compilation techniques;
see Chapter 3 for more information.
5: BASIC Stamp Command Reference – LCDCMD
LCDCMD
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
LCDCMD Pin, Command
Function
Send a command to an LCD display.
• Pin is a variable/constant/expression (0 – 1 or 8 – 9) that specifies
which I/O pins to use. The LCD requires, at most, seven I/O pins
to operate. Note that LCDCMD, LCDIN and LCDOUT use a 4-bit
interface to the LCD which requires a specific initialization sequence
before LCDIN and LCDOUT can be used. Specifics on the
initialization sequence will follow. The Pin argument serves a
double purpose; specifying the first pin and, indirectly, the group of
other required pins. See explanation below. All I/O pins will be set
to output mode.
• Command is a variable/constant/expression (0 – 255) indicating the
LCD command to send.
Quick Facts
Table 5.43: LCDCMD Quick Facts.
Values for Pin
I/O Pin
Arrangement
when Pin is
0 or 1
I/O Pin
Arrangement
when Pin is
8 or 9
Special Notes
Related Commands
BS2p, BS2pe, and BS2px
0, 1, 8 or 9
0 or 1 (depending on pin): LCD Enable (E) pin
2: LCD Read/Write (R/W) pin
3: LCD Register Select (RS) pin
4 – 7: LCD Data Buss (DB4 – DB7, respectively) pins
8 or 9 (depending on pin): LCD Enable (E) pin
10: LCD Read/Write (R/W) pin
11: LCD Register Select (RS) pin
12 – 15: LCD Data Buss (DB4 – DB7, respectively) pins
LCDCMD is designed to use the LCD's 4-bit mode only.
LCDIN and LCDOUT
Explanation
NOTE: LCDCMD, LCDIN and
LCDOUT use a 4-bit interface to the
LCD which requires a specific
initialization sequence before LCDIN
and LCDOUT can be used; read more
below.
The three LCD commands (LCDCMD, LCDIN and LCDOUT) allow the
BS2p, BS2pe, and BS2px to interface directly to standard LCD displays that
feature a Hitachi 44780 controller (part #HD44780A). This includes many
1 x 16, 2 x 16 and 4 x 20 character LCD displays.
The Hitachi 44780 LCD controller supports a number of special
instructions for initializing the display, moving the cursor, changing the
default layout, etc. The LCDCMD command is used to send one of these
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 249
LCDCMD – BASIC Stamp Command Reference
instructions to the LCD. It is most commonly used to initialize the display
upon a power-up or reset condition.
The following is an example of the LCDCMD command:
A SIMPLE LCDCMD EXAMPLE.
LCDOUT 0, 24
The above code will send the Scroll Left command (represented by the
number 24) to the LCD whose enable pin is connected to I/O pin 0. This
will cause the LCD display to scroll, or shift, the entire display one
character to the left.
You may have noticed that the Pin argument in the example above was 0.
The LCDCMD command actually uses more than just this I/O pin,
however. The LCDCMD command requires seven I/O pins. This is
because the standard LCD displays have a parallel interface, rather than a
serial one. The Pin argument can be the numbers 0, 1, 8 or 9 and will
result in the use of the I/O pins shown in Table 5.43. Figure 5.14 shows
the required wiring for the above command to work.
WIRING THE BASIC STAMP TO AN LCD.
Figure 5.14: Example LCD Circuit.
Shown with all connections
necessary for the LCDCMD, LCDIN
and LCDOUT commands.
Page 250 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – LCDCMD
Note that we could have used 1 for the Pin argument and moved the
LCD's Enable pin (pin 6) to I/O pin 1. Similarly, using 9 for the Pin
argument would have required us to wire the LCD's pins to I/O pins 9
through 15, rather than I/O pins 0 and 2 through 7.
INITIALIZING THE LCD; THE MOST
IMPORTANT STEP!
When the LCD is first powered-up, it defaults to an 8-bit interface and
must be configured for a 4-bit buss before sending commands like the one
shown above. This process is known as initializing the LCD and is the
first thing your program should do upon starting up. The following code
is a good example of LCD initialization.
Init_LCD:
PAUSE 1000
LCDCMD 0, %00110000
PAUSE 5
LCDCMD 0, %00110000
PAUSE 0
LCDCMD 0, %00110000
PAUSE 0
LCDCMD 0, %00100000
LCDCMD 0, %00101000
LCDCMD 0, %00001100
LCDCMD 0, %00000110
' allow LCD to self-initialize first
' send wakeup sequence to LCD
' pause required by LCD specs
' pause required by LCD specs
'
'
'
'
'
pause required by LCD specs
set data bus to 4-bit mode
set to 2-line mode with 5x8 font
display on without cursor
auto-increment cursor
This initialization code is the most commonly used sequence for a 2 x 16
and 4 x 20 LCD display (the 2-line mode instruction sets the 4 x 20 to 4-line
mode). The PAUSE 1000 command is optional, but only if your program
takes more than approximately 700 ms before it executes the InitLCD code
above. Without it, upon powering your circuit, the BASIC Stamp may talk
to the LCD too early, the LCD will then miss some of the commands and
the display will operate strangely, or not at all.
Do not change the "wake-up" and "4-bit mode" sequence commands.
However, the commands below the line that says, "Set data bus to 4-bit
mode" may be modified to set other desired modes.
COMMON LCD COMMANDS.
Table 5.44 shows the most commonly used LCD commands. Here's an
example:
LCDCMD 0, 16
This will make the LCD's cursor move left by one character (16 is the
Cursor Left command), even if the cursor is not visible. The next character
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 251
LCDCMD – BASIC Stamp Command Reference
printed on the display (with the LCDOUT command) will appear at the
current cursor's location. Here's another example:
LCDCMD 0, 128 + 64
The above command will move the cursor to the first character position on
the second line (on a 2 x 16 display). 128 is the Move To Display Address
command and 64 is the location number. See the "Character Positioning"
section, below, for more information.
Do Nothing
Clear Display
Home Display
Inc Cursor
Display Off
Display On
Blinking Cursor
Underline Cursor
Cursor Left
Cursor Right
Scroll Left
Scroll Right
Move To CGRAM
Address
Move To DDRAM
Address
Command
(in decimal)
0
1
2
6
8
12
13
14
16
20
24
28
Description
Don't perform any special operation.
Clear the display and move cursor to home position.
Move cursor and display to home position.
Set cursor direction to right, without a display shift.
Turn off display (display data is retained).
Turn on display without cursor (display is restored).
Turn on display with blinking cursor.
Turn on display with underline cursor.
Move cursor left one character.
Move cursor right one character.
Scroll display left one character.
Scroll display right one character.
64 + address
Move pointer to character RAM location.
128 + address
Move cursor to Display Data RAM location.
Table 5.44: Common LCD
Commands. These are supported
by LCDs with the Hitachi 44780
controller.
While most users will only need the commands shown in Table 5.44
above, Table 5.45 below details all of the instructions supported by the
LCD (for advanced users). Many instructions are multipurpose,
depending on the state of special bits. Clever manipulation of the
instruction bits will allow for powerful control of the LCD.
A NOTE ABOUT ADVANCED LCD
COMMANDS.
The last command shown above (Move To DDRAM Address) is used to
move the cursor to a specific position on the LCD. The LCD's DDRAM
(Display Data RAM) is a fixed size with a unique position number for each
character cell. The viewable portion of the DDRAM depends on the LCD's
logical view position (which can be altered with the Scroll Display
command). The default view position is called the Home position; it
means that the display's upper left character corresponds to DDRAM
CHARACTER POSITIONING: MOVING THE
CURSOR.
Page 252 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – LCDCMD
location 0. Figure 5.15 indicates the position numbers for characters on the
LCD screen.
Table 5.45: All LCD Commands
(for advanced users). These are
supported by LCDs with the
Hitachi 44780 controller.
Command Code (in binary)
6
5
4
3
2
1
7
Description
0
Clear Display
0
0
0
0
0
0
0
1
Home Display
0
0
0
0
0
0
1
0
Entry Mode
0
0
0
0
0
1
M
S
Display/Cursor
0
0
0
0
1
D
U
B
Scroll Display /
Shift Cursor
0
0
0
1
C
M
0
0
Function Set
0
0
1
B
L
F
0
0
1
A
A
A
A
A
A
A
A
A
A
A
A
A
Move To CGRAM
0
Address
Move To DDRAM
1
Address
Clear entire display and move
cursor home (address 0).
Move cursor home and return
display to home position.
Sets cursor direction (M: 0=left,
1=right) and display scrolling (S:
0=no scroll, 1=scroll)
Sets display on/off (D), underline
cursor (U) and blinking block
cursor (B). (0=off, 1=on)
Shifts display or cursor (C:
0=cursor, 1=display) left or right
(M: 0=left, 1=right).
Sets buss size (B: 0=4-bits,
1=8-bits), number of lines (L:
0=1-line, 1=2-lines) and font size
(F: 0=5x8, 1=5x10)
Move pointer to character RAM
location specified by address (A)
Move cursor to display RAM
location specified by address (A)
Note that Figure 5.15 shows the most common DDRAM mapping, though
some LCD's may have organized the DDRAM differently. A little
experimentation with your LCD may reveal this.
2 x 16 Display
Figure 5.15: LCD Character
Positions.
NOTE: Many 1 x 16 displays
conform to the position numbers
shown on Line 1 of the 2 x 16
display.
On-screen positions*
Line 1: 0
1
2
3
4
5
6
7
8
Off-screen positions*
9 10 11 12 13 14 15 16
… 39
Line 2: 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 … 103
4 x 20 Display
Line 1:
0
1
2
3
4
5
6
7
8
9 10 11 12 13 14 15 16 17 18 19
Line 2: 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
Line 3: 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
Line 4: 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100101 102103
*Assuming the display is in the home position.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 253
LCDCMD – BASIC Stamp Command Reference
On a standard 2 x 16 character display, the following command would
move the cursor to the third column of the second line:
LCDCMD 0, 128 + 66
The number 128 tells the LCD we wish to move the cursor and 66 is the
location number of the desired position. Similarly, sending just 128
(128 + 0) would move the cursor to the first character of the first line (the
upper left character if the display is at the home position).
You may have noticed that the 2 x 16 display has many locations that are
not visible; they are beyond the right edge of the screen. These locations
(16 – 39 and 80 to 103) become important for scrolling operations. For
example, it is possible to move the cursor to location 16, print some text
there and then issue a number of Scroll Left instructions (LCDCMD 0, 24)
to slowly scroll the text onto the display from right to left. If you did so,
the DDRAM positions that were on the left of the screen would now be
past the left edge of the screen. For example,
SCROLLING THE DISPLAY.
LCDCMD 0, 24
LCDCMD 0, 24
would cause the screen to scroll to the left by two characters. At this point,
the upper-left character in the display would actually be DDRAM location
2 and the lower-left character would be DDRAM location 66. Locations 0,
1, 64 and 65 would be off the left edge of the LCD and would no longer be
visible. Some interesting effects can be achieved by taking advantage of
this feature.
The 4 x 20 LCD has a strange DDRAM map. The upper-right character is
location 19 and the next location, 20, appears as the first character of the
third line. This strange mapping is due to constraints in the LCD
controller and the manufacturers design, and unfortunately makes the
scrolling features virtually useless on the 4 x 20 displays.
NOTES ON DDRAM MAPPING FOR 4 X 20
LCDS.
Even though the LCD requires many pins to talk to it, only the Enable pin
needs to remain dedicated to the LCD and all the other pins can be
multiplexed (shared) with certain other devices (if wired carefully). In
addition, the I/O pin connected to the LCD's R/W pin is only necessary if
the LCDIN command will be used in the application. If the LCDIN
command will not be used, LCD pin 5 (R/W pin) can be connected to
DETAILS ON LCD WIRING.
Page 254 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – LCDCMD
ground, the 4 resistors on LCD pins 7-10 may be removed (connecting pins
7-10 directly to ground). Note that even though this change will leave
BASIC Stamp I/O pin 2 disconnected, it will still be set to output mode
for each LCDCMD and LCDOUT command executed.
Demo Program (LCDINIT.bsp)
NOTE: This example program can be
used with the BS2p, BS2pe, and BS2px
by changing the $STAMP directive
accordingly.
'
'
'
'
'
LCDINIT.bsp
This program demonstrates initialization and printing on a 2 x 16
character LCD display. The set of "LCD constants", below, are provided
as pre-defined and useful LCD commands, though not all are actually
used in this program.
' {$STAMP BS2p}
' {$PBASIC 2.5}
#IF ($STAMP < BS2P) #THEN
#ERROR "Program requires BS2p, BS2pe or BS2px."
#ENDIF
Lcd
PIN
0
LcdCls
LcdHome
LcdCrsrL
LcdCrsrR
LcdDispL
LcdDispR
LcdDDRam
LcdCGRam
LcdLine1
LcdLine2
CON
CON
CON
CON
CON
CON
CON
CON
CON
CON
$01
$02
$10
$14
$18
$1C
$80
$40
$80
$C0
Init_LCD:
PAUSE 1000
LCDCMD Lcd,
PAUSE 5
LCDCMD Lcd,
PAUSE 0
LCDCMD Lcd,
PAUSE 0
LCDCMD Lcd,
LCDCMD Lcd,
LCDCMD Lcd,
LCDCMD Lcd,
%00110000
'
'
'
'
'
'
'
'
'
'
clear the LCD
move cursor home
move cursor left
move cursor right
shift chars left
shift chars right
Display Data RAM
Character Generator RAM
DDRAM address of line 1
DDRAM address of line 2
' allow LCD to self-initialize first
' send wakeup sequence to LCD
' pause required by LCD specs
%00110000
' pause required by LCD specs
%00110000
%00100000
%00101000
%00001100
%00000110
'
'
'
'
'
pause required by LCD specs
set data bus to 4-bit mode
set to 2-line mode with 5x8 font
display on without cursor
auto-increment cursor
Main:
DO
LCDOUT Lcd, LcdCls, ["Hello, World!"]
LCDOUT Lcd, LcdLine2, ["How are you?"]
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 255
LCDCMD – BASIC Stamp Command Reference
PAUSE 3000
LCDCMD Lcd, LcdCls
PAUSE 500
LOOP
END
Page 256 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – LCDIN
LCDIN
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
LCDIN Pin, Command, [ InputData ]
Function
Receive data from an LCD display.
• Pin is a variable/constant/expression (0 – 1 or 8 – 9) that specifies
which I/O pins to use. The LCD requires, at most, seven I/O pins
to operate. The Pin argument serves a double purpose; specifying
the first pin and, indirectly, the group of other required pins. See
explanation below. All I/O pins will be set to output mode initially
and the upper I/O pins (4 – 7 or 12 – 15) will be set to input mode by
the end of the LCDIN command.
• Command is a variable/constant/expression (0 – 255) indicating the
LCD command to send.
• InputData is a list of variables and formatters that tells LCDIN what
to do with incoming data. LCDIN can store data in a variable or
array, interpret numeric text (decimal, binary, or hex) and store the
corresponding value in a variable, wait for a fixed or variable
sequence of bytes, or ignore a specified number of bytes. These
actions can be combined in any order in the InputData list.
Quick Facts
Table 5.46: LCDIN Quick Facts.
Values for Pin
I/O Pin
Arrangement
when Pin is
0 or 1
I/O Pin
Arrangement
when Pin is
8 or 9
Special Notes
Related
Commands
BS2p, BS2pe, and BS2px
0, 1, 8 or 9
0 or 1 (depending on pin): LCD Enable (E) pin
2: LCD Read/Write (R/W) pin
3: LCD Register Select (RS) pin
4 – 7: LCD Data Buss (DB4 – DB7, respectively) pins
8 or 9 (depending on pin): LCD Enable (E) pin
10: LCD Read/Write (R/W) pin
11: LCD Register Select (RS) pin
12 – 15: LCD Data Buss (DB4 – DB7, respectively) pins
LCDIN is designed to use the LCD's 4-bit mode only.
LCDCMD and LCDOUT
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 257
LCDIN – BASIC Stamp Command Reference
Explanation
The three LCD commands (LCDCMD, LCDIN and LCDOUT) allow the
BS2p, BS2pe, and BS2px to interface directly to standard LCD displays that
feature a Hitachi 44780 controller (part #HD44780A). This includes many
1 x 16, 2 x 16 and 4 x 20 character LCD displays.
NOTE: LCDCMD, LCDIN and
LCDOUT use a 4-bit interface to the
LCD which requires a specific
initialization sequence before LCDIN
and LCDOUT can be used; read more
below.
The LCDIN command is used to send one instruction and then receive at
least one data byte from the LCD's Character Generator RAM or Display
Data RAM. The following is an example of the LCDIN command:
A SIMPLE LCDIN EXAMPLE.
char
LCDIN
VAR
Byte
0, 128, [char]
The above code will read the character value at location 0 of the DDRAM.
See the "Character Positioning" section, of the LCDCMD command
description on page 252 for more information.
The LCDIN command actually uses more than just the I/O pin specified
by the Pin argument. The LCDIN command requires seven I/O pins. This
is because the standard LCD displays have a parallel interface, rather than
a serial one. The Pin argument can be the numbers 0, 1, 8 or 9 and will
result in the use of the I/O pins shown in Table 5.46. Please refer to the
LCDCMD command description for information on page properly wiring
the LCD display.
TWO VERY IMPORTANT STEPS:
1) WIRING THE BASIC STAMP TO AN LCD.
2) INITIALIZING THE LCD.
When the LCD is first powered-up, it defaults to an 8-bit interface and
must be properly configured for a 4-bit buss before sending commands
like the one shown above. This process is known as initializing the LCD
and is the first thing your program should do upon starting up. Please
refer to the LCDCMD command description for information on properly
initializing the LCD display.
The LCDIN command's InputData argument is similar to the SERIN
command's InputData argument. This means data can be received as
ASCII character values, decimal, hexadecimal and binary translations and
string data as in the examples below (assume the LCD display has "Value:
3A:101" starting at the first character of the first line on the screen).
Page 258 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
RECEIVING FORMATTED DATA.
5: BASIC Stamp Command Reference – LCDIN
value
LCDIN
LCDIN
LCDIN
LCDIN
LCDIN
0,
0,
0,
0,
0,
VAR
128,
128,
128,
128,
128,
Byte(13)
[value]
[DEC value]
[HEX value]
[BIN value]
[STR value\13]
'receive
'receive
'receive
'receive
'receive
the
the
the
the
the
ASCII value for "V"
number 3.
number $3A.
number %101.
string "Value: 3A:101"
Table 5.47 and Table 5.48 list all the special formatters and conversion
formatters available to the LCDIN command. See the SERIN command for
additional information and examples of their use.
Some possible uses of the LCDIN command are 1) in combination with the
LCDOUT command to store and read data from the unused DDRAM or
CGRAM locations (as extra variable space), 2) to verify that the data from
a previous LCDOUT command was received and processed properly by
the LCD, and 3) to read character data from CGRAM for the purposes of
modifying it and storing it as a custom character.
Table 5.47: LCDIN Special
Formatters.
Special Formatter
SPSTR L
STR ByteArray \L {\E}
WAIT (Value)
WAITSTR ByteArray {\L}
SKIP Length
Action
Input a character string of length L bytes (up to 126) into Scratch
Pad RAM, starting at location 0. Use GET to retrieve the
characters.
Input a character string of length L into an array. If specified, an
end character E causes the string input to end before reaching
length L. Remaining bytes are filled with 0s (zeros).
Wait for a sequence of bytes specified by value. Value can be
numbers separated by commas or quoted text (ex: 65, 66, 67 or
“ABC”). The WAIT formatter is limited to a maximum of six
characters.
Wait for a sequence of bytes matching a string stored in an array
variable, optionally limited to L characters. If the optional L
argument is left off, the end of the array-string must be marked
by a byte containing a zero (0).
Ignore Length bytes of characters.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 259
LCDIN – BASIC Stamp Command Reference
Conversion
Formatter
Type of Number
DEC{1..5}
SDEC{1..5}
Decimal, optionally limited to 1 – 5 digits
Signed decimal, optionally limited to 1 – 5
digits
Hexadecimal, optionally limited to 1 – 4 digits
HEX{1..4}
SHEX{1..4}
IHEX{1..4}
ISHEX{1..4}
BIN{1..16}
SBIN{1..16}
IBIN{1..16}
ISBIN{1..16}
NUM
2
3
4
5
Notes
1
1,2
0 through 9, A
through F
-, 0 through 9,
A through F
$, 0 through 9,
A through F
-, $, 0 through
9, A through F
0, 1
-, 0, 1
1,3,5
1
1,2
%, 0, 1
1,4
-, %, 0, 1
1,2,4
$, %, 0 through
9, A through F
1, 3, 4
1,2,3
1,3,4
1,2,3,4
-, $, %,
0 through 9,
1,2,3,4
A through F
All numeric conversions will continue to accept new data until receiving either the specified
number of digits (ex: three digits for DEC3) or a non-numeric character.
To be recognized as part of a number, the minus sign (-) must immediately precede a
numeric character. The minus sign character occurring in non-numeric text is ignored and
any character (including a space) between a minus and a number causes the minus to be
ignored.
The hexadecimal formatters are not case-sensitive; “a” through “f” means the same as “A”
through “F”.
Indicated hexadecimal and binary formatters ignore all characters, even valid numerics,
until they receive the appropriate prefix ($ for hexadecimal, % for binary). The indicated
formatters can differentiate between text and hexadecimal (ex: ABC would be interpreted
by HEX as a number but IHEX would ignore it unless expressed as $ABC). Likewise, the
binary version can distinguish the decimal number 10 from the binary number %10. A
prefix occurring in non-numeric text is ignored, and any character (including a space)
between a prefix and a number causes the prefix to be ignored. Indicated, signed
formatters require that the minus sign come before the prefix, as in -$1B45.
The HEX modifier can be used for Decimal to BCD Conversion. See “Hex to BCD
Conversion” on page 97.
SNUM
1
Signed hexadecimal, optionally limited to
1 – 4 digits
Indicated hexadecimal, optionally limited to
1 – 4 digits
Signed, indicated hexadecimal, optionally
limited to 1 – 4 digits
Binary, optionally limited to 1 – 16 digits
Signed binary, optionally limited to 1 – 16
digits
Indicated binary, optionally limited to 1 – 16
digits
Signed, indicated binary, optionally limited
to 1 – 16 digits
Generic numeric input (decimal, hexadecimal
or binary); hexadecimal or binary number
must be indicated
Numeric
Characters
Accepted
0 through 9
-, 0 through 9
Similar to NUM with value treated as signed
with range -32768 to +32767
For examples of all conversion formatters and how they process incoming
data see Appendix C.
Page 260 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Table 5.48: LCDIN Conversion
Formatters
5: BASIC Stamp Command Reference – LCDIN
Demo Program (LCDIN.bsp)
NOTE: This example program can be
used with the BS2p, BS2pe, and
BS2px. This program uses conditional
compilation techniques; see Chapter 3
for more information.
' LCDIN.bsp
' This program demonstrates initialization, printing and reading
' from a 2 x 16 character LCD display.
' {$STAMP BS2p}
' {$PBASIC 2.5}
#IF ($STAMP < BS2P) #THEN
#ERROR "Program requires BS2p, BS2pe or BS2px."
#ENDIF
Lcd
PIN
0
LcdCls
LcdHome
LcdCrsrL
LcdCrsrR
LcdDispL
LcdDispR
LcdDDRam
LcdCGRam
LcdLine1
LcdLine2
CON
CON
CON
CON
CON
CON
CON
CON
CON
CON
$01
$02
$10
$14
$18
$1C
$80
$40
$80
$C0
char
VAR
Byte(16)
Init_LCD:
PAUSE 1000
LCDCMD Lcd,
PAUSE 5
LCDCMD Lcd,
PAUSE 0
LCDCMD Lcd,
PAUSE 0
LCDCMD Lcd,
LCDCMD Lcd,
LCDCMD Lcd,
LCDCMD Lcd,
%00110000
'
'
'
'
'
'
'
'
'
'
clear the LCD
move cursor home
move cursor left
move cursor right
shift chars left
shift chars right
Display Data RAM
Character Generator RAM
DDRAM address of line 1
DDRAM address of line 2
' allow LCD to self-initialize first
' send wakeup sequence to LCD
' pause required by LCD specs
%00110000
' pause required by LCD specs
%00110000
%00100000
%00101000
%00001100
%00000110
'
'
'
'
'
pause required by LCD specs
set data bus to 4-bit mode
set to 2-line mode with 5x8 font
display on without cursor
auto-increment cursor
Main:
DO
LCDOUT Lcd, LcdCls, ["Hello!"]
GOSUB Read_LCD_Screen
PAUSE 3000
LCDOUT Lcd, LcdCls, ["I'm a 2x16 LCD!"]
GOSUB Read_LCD_Screen
PAUSE 3000
LOOP
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 261
LCDIN – BASIC Stamp Command Reference
Read_LCD_Screen:
DEBUG "LCD now says: "
LCDIN Lcd, LcdLine1, [STR char\16]
DEBUG STR char\16, CR
RETURN
Page 262 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – LCDOUT
LCDOUT
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
LCDOUT Pin, Command, [ OutputData ]
Function
Send data to an LCD display.
• Pin is a variable/constant/expression (0 – 1 or 8 – 9) that specifies
which I/O pins to use. The LCD requires, at most, seven I/O pins
to operate. The Pin argument serves a double purpose; specifying
the first pin and, indirectly, the group of other required pins. See
explanation below. All I/O pins will be set to output mode.
• Command is a variable/constant/expression (0 – 255) indicating an
LCD command to send.
• OutputData is a list of variables, constants, expressions and
formatters that tells LCDOUT how to format outgoing data.
LCDOUT can transmit individual or repeating bytes, convert values
into decimal, hex or binary text representations, or transmit strings
of bytes from variable arrays. These actions can be combined in any
order in the OutputData list.
Quick Facts
Table 5.49: LCDOUT Quick Facts.
Values for Pin
I/O Pin Arrangement
when Pin is
0 or 1
I/O Pin Arrangement
when Pin is
8 or 9
Special Notes
Related Commands
BS2p, BS2pe, and BS2px
0, 1, 8 or 9
0 or 1 (depending on pin): LCD Enable (E) pin
2: LCD Read/Write (R/W) pin
3: LCD Register Select (RS) pin
4 – 7: LCD Data Buss (DB4 – DB7, respectively) pins
8 or 9 (depending on pin): LCD Enable (E) pin
10: LCD Read/Write (R/W) pin
11: LCD Register Select (RS) pin
12 – 15: LCD Data Buss (DB4 – DB7, respectively) pins
LCDOUT is designed to use the LCD's 4-bit mode only.
LCDCMD and LCDIN
Explanation
NOTE: LCDCMD, LCDIN and
LCDOUT use a 4-bit interface to the
LCD which requires a specific
initialization sequence before LCDIN
and LCDOUT can be used; read more
below.
The three LCD commands (LCDCMD, LCDIN and LCDOUT) allow the
BS2p, BS2pe, and BS2px to interface directly to standard LCD displays that
feature a Hitachi 44780 controller (part #HD44780A). This includes many
1 x 16, 2 x 16 and 4 x 20 character LCD displays.
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 263
LCDOUT – BASIC Stamp Command Reference
The LCDOUT command is used to send one instruction followed by at
least one data byte to the LCD. The data that is output is written to the
LCD's Character Generator RAM or Display Data RAM. The following is
an example of the LCDOUT command:
LCDOUT
A SIMPLE LCDOUT EXAMPLE.
0, 1, ["Hello World!"]
The above code will clear the LCD screen and then send "Hello World!" to
the screen. The first argument (0) is the starting I/O pin number and the
second argument (1) is the LCD's instruction for Clear Screen.
The LCDOUT command actually uses more than just the I/O pin specified
by the Pin argument. The LCDOUT command requires seven I/O pins.
This is because the standard LCD displays have a parallel interface, rather
than a serial one. The Pin argument can be the numbers 0, 1, 8 or 9 and
will result in the use of the I/O pins shown in Table 5.49. Please refer to
the LCDCMD command description for information on properly wiring
the LCD display.
TWO VERY IMPORTANT STEPS:
1) WIRING THE BASIC STAMP TO AN LCD.
2) INITIALIZING THE LCD.
When the LCD is first powered-up, it defaults to an 8-bit interface and
must be properly configured for a 4-bit buss before sending commands
like the one shown above. This process is known as initializing the LCD
and is the first thing your program should do upon starting up. Please
refer to the LCDCMD command description for information on properly
initializing the LCD display.
The LCDOUT command's OutputData argument is exactly like that of the
DEBUG and SEROUT command's OutputData argument. This means data
can be sent as literal text, ASCII character values, repetitive values,
decimal, hexadecimal and binary translations and string data as in the
examples below.
value
VAR
Byte
value = 65
LCDOUT
LCDOUT
LCDOUT
LCDOUT
LCDOUT
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
[value]
[REP value\5]
[DEC value]
[HEX value]
[BIN value]
'
'
'
'
'
send
send
send
send
send
"A"
"AAAAA"
"6" and "5"
"4" and "1"
"1000001"
Page 264 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
SENDING AND FORMATTING DATA.
5: BASIC Stamp Command Reference – LCDOUT
Table 5.50 and Table 5.51 list all the available conversion formatters and
special formatters available to the LCDOUT command. See the DEBUG
and SEROUT commands for additional information and examples of their
use.
Table 5.50: LCDOUT Conversion
Formatters.
Conversion
Formatter
DEC{1..5}
SDEC{1..5}
HEX{1..4}
SHEX{1..4}
IHEX{1..4}
Type of Number
Notes
Decimal, optionally fixed to 1 – 5 digits
1
Signed decimal, optionally fixed to 1 – 5 digits
1,2
Hexadecimal, optionally fixed to 1 – 4 digits
1,3
Signed hexadecimal, optionally fixed to 1 – 4 digits
1,2
Indicated hexadecimal, optionally fixed to 1 – 4 digits ($ prefix)
1
Signed, indicated hexadecimal, optionally fixed to 1 – 4 digits
ISHEX{1..4}
1,2
($ prefix)
BIN{1..16}
Binary, optionally fixed to 1 – 16 digits
1
SBIN{1..16}
Signed binary, optionally fixed to 1 – 16 digits
1,2
IBIN{1..16}
Indicated binary, optionally fixed to 1 – 16 digits (% prefix)
1
ISBIN{1..16} Signed, indicated binary, optionally fixed to 1 – 16 digits (% prefix)
1,2
1 Fixed-digit formatters like DEC4 will pad the number with leading 0s if necessary; ex:
DEC4 65 sends 0065. If a number is larger than the specified number of digits, the
leading digits will be dropped; ex: DEC4 56422 sends 6422.
2 Signed modifiers work under two's complement rules.
3 The HEX modifier can be used for BCD to Decimal Conversion. See “Hex to BCD
Conversion” on page 97.
Table 5.51: LCDOUT Special
Formatters.
Special Formatter
?
ASC ?
STR ByteArray {\L}
REP Byte \L
USING THE COMMAND ARGUMENT.
Action
Displays "symbol = x' + carriage return; where x is a number.
Default format is decimal, but may be combined with conversion
formatters (ex: BIN ? x to display "x = binary_number").
Displays "symbol = 'x'" + carriage return; where x is an ASCII
character.
Send character string from an array. The optional \L argument
can be used to limit the output to L characters, otherwise,
characters will be sent up to the first byte equal to 0 or the end of
RAM space is reached.
Send a string consisting of Byte repeated L times
(ex: REP "X"\10 sends "XXXXXXXXXX").
The Command argument is useful for proceeding a set of data with a
special LCD instruction. For example, the code below will move the
cursor to location 64 (the first character on the second line) and print "Hi":
LCDOUT
0, 128 + 64, ["Hi"]
The next example, below, will turn on the blinking block cursor and print
"Yo!":
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 265
LCDOUT – BASIC Stamp Command Reference
LCDOUT
0, 13, ["Yo!"]
Most of the time, you will want to send data without preceding it with a
command. To do this, simply use 0 for the Command argument, as in:
LCDOUT
0, 0, ["Hello there!"]
Another use for the LCDOUT command is to access and create custom
characters. The Hitachi 44780 controller has a built-in character set that is
similar to the ASCII character set (at least for the first 128 characters).
Most of these characters are stored in ROM and are not changeable,
however, the first eight characters (ASCII 0 though 7) are programmable.
CREATING CUSTOM CHARACTERS.
Each of the programmable characters is five pixels wide and eight pixels
tall. It takes eight bytes to describe each character; one byte per row (the
left-most three bits are ignored). For example, the character at ASCII
location 0 is defined by the bit patterns stored in bytes 0 through 7 of
Character Generator RAM (CGRAM). The character at ASCII location 1 is
defined by the bit patterns stored in bytes 8 through 15 of CGRAM, and so
on.
To create a custom character, use some graph paper to plot out the bit
pattern (on and off pixels) in a 5 x 8 pattern, as shown in Figure 5.16. Then
calculate the corresponding binary value of the bit pattern for each of the
eight rows of character data.
Character Cell Structure and Data
---------Bits--------4 3 2 1 0
Byte 0:
Byte 1:
Byte 2:
Byte 3:
Byte 4:
Byte 5:
Byte 6:
Byte 7:
Binary Values
Decimal Values
xxx00000
xxx01010
xxx00000
xxx00100
xxx10001
xxx01110
xxx00000
xxx00000
00
10
00
04
17
14
00
00
After the data is calculated for each character (8 byte values per character),
use the LCDOUT command with the "Move To CGRAM Address"
instruction to insert the data into the character's CGRAM locations. For
example, the code below will store the character shown in Figure 5.16 into
Page 266 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Figure 5.16: LCD Character
Structure.
5: BASIC Stamp Command Reference – LCDOUT
character 0's CGRAM data locations. Then it will place the cursor back on
the display (DDRAM) and print the character on the screen.
LCDOUT
LCDOUT
0, 64+0, [00, 10, 00, 04, 17, 14, 00, 00]
0, 128+0, ["Custom Char: ", 0]
The number 64 in the Command argument is the LCD's "Move to CGRAM
Address" instruction and the 0 that is added to it is the location of the first
row of data for the character 0. The LCDOUT command will write the
first OutputData value (00) to this location, the second OutputData value
(10) to location 1, etc. If we wanted this custom character to affect
character 1, instead of 0, we'd have to adjust the value of the "Move To..."
command, i.e.: 64+8. To affect character 2, we'd use 64+16.
To try the example above, don't forget to execute the LCD initialization
code (shown in the LCDCMD description) first and never forget to move
the cursor back to the screen (as with the last command, above) when
you're done writing the character data to CGRAM.
Demo Program (LCDOUT.bsp)
NOTE: This example program can be
used with the BS2p, BS2pe, and
BS2px. This program uses conditional
compilation techniques; see Chapter 3
for more information.
' LCDOUT.bsp
' This program demonstrates initialization and printing on a 2x16
' character LCD display.
' {$STAMP BS2p}
' {$PBASIC 2.5}
#IF ($STAMP < BS2P) #THEN
#ERROR "Program requires BS2p, BS2pe or BS2px."
#ENDIF
Lcd
PIN
0
LcdCls
LcdHome
LcdCrsrL
LcdCrsrR
LcdDispL
LcdDispR
LcdDDRam
LcdCGRam
LcdLine1
LcdLine2
CON
CON
CON
CON
CON
CON
CON
CON
CON
CON
$01
$02
$10
$14
$18
$1C
$80
$40
$80
$C0
Init_LCD:
PAUSE 1000
'
'
'
'
'
'
'
'
'
'
clear the LCD
move cursor home
move cursor left
move cursor right
shift chars left
shift chars right
Display Data RAM
Character Generator RAM
DDRAM address of line 1
DDRAM address of line 2
' allow LCD to self-initialize first
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 267
LCDOUT – BASIC Stamp Command Reference
LCDCMD Lcd,
PAUSE 5
LCDCMD Lcd,
PAUSE 0
LCDCMD Lcd,
PAUSE 0
LCDCMD Lcd,
LCDCMD Lcd,
LCDCMD Lcd,
LCDCMD Lcd,
%00110000
' send wakeup sequence to LCD
' pause required by LCD specs
%00110000
' pause required by LCD specs
%00110000
%00100000
%00101000
%00001100
%00000110
'
'
'
'
'
pause required by LCD specs
set data bus to 4-bit mode
set to 2-line mode with 5x8 font
display on without cursor
auto-increment cursor
LCDOUT Lcd, LcdCGRam,
' load custom character map
[$00, $0A, $0A, $00, $11, $0E, $06, $00]
Main:
DO
LCDOUT Lcd,
PAUSE 750
LCDOUT Lcd,
PAUSE 1500
LCDCMD Lcd,
LCDOUT Lcd,
LCDOUT Lcd,
PAUSE 2000
LOOP
END
LcdCls, ["Hello my friend."]
LcdLine2, ["How are you?"]
LcdCls
LcdLine1 + 1, ["I'm doing just"]
LcdLine2 + 4, ["fine! ", 0]
Page 268 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – LET
LET
1
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
{ LET } Variable = Value
Function
Sets Variable equal to the value of Value.
• Value is a variable/constant/expression. (0-65535).
• Variable is a variable which will be set equal to Value.
Explanation
LET is an optional instruction for the BASIC Stamp 1 that can be used with
variable assignment statements, such as A = 5 and B = A + 2, etc. This
instruction is not required and only exists on the BASIC Stamp 1. LET was
a commonly used command in early forms of BASIC, and was originally
included in the BS1 command set to accommodate programmers from that
generation. Parallax recommends that all new BASIC Stamp 1 programs
use assignment statements without the LET command.
1
Demo Program (LET.bs1)
'
'
'
'
'
LET.bs1
This example demonstrates the use of LET in assignment statements, which
is optional and not recommended. Note that the Lunchtime and
Dinnertime routines do essentially the same thing, but the Dinnertime
method is recommended(even though the pricing scheme is not!)
' {$PBASIC 1.0}
' {$STAMP BS1}
SYMBOL
SYMBOL
SYMBOL
SYMBOL
SYMBOL
salad
bread
soup
lunch
dinner
=
=
=
=
=
B1
B2
B3
B4
B5
Lunchtime:
LET salad
= 3
LET bread
= 1
LET soup
= 4
LUNCH = salad + bread + soup
DEBUG "lunch = $", #lunch, "plus local tax.", CR
Dinnertime:
salad
= 4
bread
= 2
soup
= 5
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 269
LET – BASIC Stamp Command Reference
dinner = salad + bread + soup
DEBUG "Dinner = $",# lunch, "plus local tax.", CR
Page 270 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
5: BASIC Stamp Command Reference – LOOKDOWN
LOOKDOWN
1
All
2
BS1
BS2
BS2e BS2sx BS2p BS2pe BS2px
LOOKDOWN Target, ( Value0, Value1, ...ValueN ), Variable
LOOKDOWN Target, { ComparisonOp } [ Value0, Value1, ...ValueN ], Variable
Function
1
NOTE: Expressions are not allowed as
arguments on the BS1.
All
2
Compare Target value to a list of values and store the index number of the
first value that matches into Variable. If no value in the list matches,
Variable is left unaffected. On all BS2 models, the optional ComparisonOp is
used as criteria for the match; the default criteria is "equal to."
• Target is a variable/constant/expression (0 – 65535) to be compared
to the values in the list.
• ComparisonOp is an optional comparison operator (as described in
Table 5.53) to be used as the criteria when comparing values. When
no ComparisonOp is specified, equal to (=) is assumed. This
argument is not available on the BS1.
• Values are variables/constants/expressions (0 – 65535) to be
compared to Target.
• Variable is a variable (usually a byte) that will be set to the index (0 –
255) of the matching value in the Values list. If no matching value is
found, Variable is left unaffected.
Quick Facts
Table 5.52: LOOKDOWN Quick
Facts.
BS1 and all BS2 Models
Limit of Value
Entries
Starting Index
Number
If value list
contains no
match…
Related
Command
256
0
Variable is left unaffected
LOOKUP
Explanation
LOOKDOWN works like the index in a book. In an index, you search for a
topic and get the page number. LOOKDOWN searches for a target value
in a list, and stores the index number of the first match in a variable. For
example:
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 271
LOOKDOWN – BASIC Stamp Command Reference
SYMBOL
SYMBOL
value
result
value
result
= 17
= 15
=
=
B0
B1
1
LOOKDOWN value, (26, 177, 13, 1, 0, 17, 99), result
DEBUG "Value matches item ", #result, "in list"
-- or -value
result
value
result
VAR
VAR
= 17
= 15
Byte
Nib
All
2
LOOKDOWN value, [26, 177, 13, 1, 0, 17, 99], result
DEBUG "Value matches item ", DEC result, " in list"
DEBUG prints, “Value matches item 5 in list” because the value (17)
matches item 5 of [26, 177, 13, 1, 0, 17, 99]. Note that index numbers count
up from 0, not 1; that is, in this list, 26 is item 0.
THE INDEX NUMBER OF THE FIRST ITEM IS
0, NOT 1.
What happens if the value doesn’t match any of the items in the list? Try
changing “Value = 17” to “Value = 2.” Since 2 is not on the list,
LOOKDOWN leaves result unaffected. Since result contained 15 before
LOOKDOWN executed, DEBUG prints “Value matches item 15 in list.”
By strategically setting the initial value of result, as we have here, your
program can be written to detect when an item was not found in the list.
Don’t forget that text phrases are just lists of byte values, so they too are
eligible for LOOKDOWN searches, as in this example:
SYMBOL
SYMBOL
value
result
value =
result =
=
=
B0
B1
"f"
255
LOOKDOWN value, ("The quick brown fox"), result
DEBUG "Value matches item ", #result, "in list"
-- or --
Page 272 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
USING TEXT IN THE VALUE LIST.
1
5: BASIC Stamp Command Reference – LOOKDOWN
All
2
value
result
value
result
VAR
VAR
=
=
Byte
Nib
"f"
255
LOOKDOWN value, ["The quick brown fox"], result
DEBUG "Value matches item ", DEC result, " in list"
DEBUG prints, “Value matches item 16 in list” because the character at
index item 16 is "f" in the phrase, “The quick brown fox”.
LOOKDOWN CAN USE VARIABLES AND
EXPRESSIONS IN THE VALUE LIST.
The examples above show LOOKDOWN working with lists of constants,
but it also works with variables and expressions also. Note, however, that
expressions are not allowed as argument on the BS1.
USING LOOKDOWN'S COMPARISON
OPERATORS.
On all BS2 models, the LOOKDOWN command can also use another
All 2 criteria (other than "equal to") for its list. All of the examples above use
LOOKDOWN’s default comparison operator, =, that searches for an exact
match. The entire list of ComaprisonOps is shown in Table 5.53. The
"greater than" comparison operator (>) is used in the following example:
value
result
value
result
VAR
VAR
=
=
Byte
Nib
17
15
LOOKDOWN value, >[26, 177, 13, 1, 0, 17, 99], result
DEBUG "Value greater than item ", DEC result, " in list"
DEBUG prints, “Value greater than item 2 in list” because the first item the
value 17 is greater than is 13 (which is item 2 in the list). Value is also
greater than items 3 and 4, but these are ignored, because LOOKDOWN
only cares about the first item that matches the criteria. This can require a
certain amount of planning in devising the order of the list. See the demo
program below.
WATCH OUT FOR UNSIGNED MATH
ERRORS WHEN USING THE COMPARISON
OPERATORS.
LOOKDOWN comparison operators (Table 5.53) use unsigned 16-bit
math. They will not work correctly with signed numbers, which are
represented internally as two’s complement (large 16-bit integers). For
example, the two’s complement representation of -99 is 65437. So
although -99 is certainly less than 0, it would appear to be larger than zero
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 273
LOOKDOWN – BASIC Stamp Command Reference
to the LOOKDOWN comparison operators. The bottom line is: Don’t used
signed numbers with LOOKDOWN comparisons.
ComparisonOp Symbol
=
>
<
>=