Parallax - What's A MicroController
Parallax - What's A MicroController
Parallax - What's A MicroController
Student Guide
VERSION 2.1
WARRANTY
Parallax 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 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.
This documentation is copyright 2003 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 Conditions of Duplication stated in the
Preface.
BASIC Stamp, Stamps in Class, and Board of Education are registered trademarks of Parallax, Inc. If you decide to
use the names BASIC Stamp, Stamps in Class, and/or Board of Education on your web page or in printed material,
you must state that "BASIC Stamp is a registered trademark of Parallax, Inc.," " Stamps in Class is a registered
trademark of Parallax, Inc.," and/or "Board of Education is a registered trademark of Parallax, Inc.," respectively,
upon the first appearance of the trademark name. Other brand and product names are trademarks or registered
trademarks of their respective holders.
ISBN 1-928982-02-6
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 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.
BASIC Stamps – With over 2,500 subscribers, 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, this list has 500 subscribers who 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.
Parallax Translators – Consisting of less than 10 people, 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.
Toddler Robot – A customer created this discussion list to discuss applications and programming of the
Parallax Toddler robot.
SX Tech – Discussion of programming the SX microcontroller with Parallax assembly language tools and
3rd party BASIC and C compilers. Approximately 600 members.
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. Approximately 250
members.
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.
Table of Contents · Page i
Table of Contents
Preface.........................................................................................................................v
Audience.........................................................................................................................v
Support and Teacher’s Guide.........................................................................................v
The Stamps in Class Curriculum ...................................................................................vi
Conditions of Duplication ..............................................................................................vii
Foreign Translations .....................................................................................................vii
Special Contributors .....................................................................................................vii
Chapter #1: Getting Started.......................................................................................1
How Many Microcontrollers Did You Use Today? ..........................................................1
The BASIC Stamp 2 - Your New Microcontroller............................................................1
Amazing Inventions with the BASIC Stamp....................................................................2
Hardware and Software ..................................................................................................5
Activity #1: Getting the Software.....................................................................................5
Activity #2: Installing the Software ................................................................................10
Activity #3: Setting Up the Hardware and Testing the System .....................................13
Activity #4: First Program..............................................................................................21
Activity #5: Looking Up Answers ..................................................................................27
Activity #6: When You’re Done .....................................................................................30
SUMMARY ...................................................................................................................33
Chapter #2: Lights on – Lights off ..........................................................................37
Indicator Lights .............................................................................................................37
Making a Light Emitting Diode (LED) Emit Light...........................................................37
Activity #1: Building and Testing the LED Circuit..........................................................38
Activity #2: On/Off Control with the BASIC Stamp........................................................47
Activity #3: Counting and Repeating.............................................................................52
Activity #4: Building and Testing a Second LED Circuit ...............................................56
Activity #5: Using Current Direction to Control a Bi-Color LED ....................................60
SUMMARY ...................................................................................................................66
Chapter #3: Digital Input - Pushbuttons.................................................................71
Found on Calculators, Hand Held Games, and Appliances .........................................71
Receiving vs. Sending High and Low Signals ..............................................................71
Activity #1: Testing a Pushbutton with an LED Circuit..................................................71
Activity #2: Reading a Pushbutton with the BASIC Stamp ...........................................75
Activity #3: Pushbutton Control of an LED Circuit ........................................................80
Activity #4: Two Pushbuttons Controlling Two LED Circuits.........................................83
Activity #5: Reaction Timer Test ...................................................................................88
SUMMARY ...................................................................................................................97
Page ii · What’s a Microcontroller?
SUMMARY .................................................................................................................253
Chapter #9: Electronic Building Blocks ...............................................................257
Those Little Black Chips .............................................................................................257
Expand Your Projects with Peripheral Integrated Circuits ..........................................258
Activity #1: Control Current Flow with a Transistor.....................................................259
Activity #2: Introducing the Digital Potentiometer .......................................................261
SUMMARY .................................................................................................................271
Chapter #10: Running the Whole Show ...............................................................273
Subsystem Integration ................................................................................................273
Activity #1: Building and Testing Each Pushbutton Circuit .........................................274
Activity #2: Building and Testing Each RC-Time Circuit .............................................277
Activity #3: Subsystem Integration Example...............................................................279
Activity #4: Developing and Adding a Software Subsystem .......................................283
SUMMARY .................................................................................................................289
Appendix A: USB to Serial Adaptor......................................................................293
Appendix B: Equipment and Parts Lists..............................................................295
Appendix C: BASIC Stamp and Carrier Board Components and Functions....299
Appendix D: Batteries and Power Supplies.........................................................303
Appendix E: Trouble-Shooting..............................................................................307
Appendix F: More About Electricity......................................................................309
Appendix G: RTTTL Format Summary .................................................................317
Index ........................................................................................................................319
Preface · Page v
Preface
This text answers the question “What’s a microcontroller?” by showing students how
they can design their own customized, intelligent inventions using the BASIC Stamp.
The activities in this text incorporate a variety of fun and interesting experiments
designed to appeal to a student’s imagination by using motion, light, sound, and tactile
feedback to introduce new concepts. These activities are designed to introduce students
to a variety of basic principles in the fields of computer programming, electricity and
electronics, mathematics and physics. Many of the activities facilitate hands-on
presentation of design practices used by engineers and technicians in the creation of
modern machines and appliances using inexpensive and easily obtainable parts.
AUDIENCE
This text is organized so that it can be used by the widest possible variety of students as
well as independent learners. Middle school students can try the examples in this text in
a guided tour fashion by simply following the check-marked instructions and instructor
supervision. At the other end of the spectrum, pre-engineering students’ problem-solving
skills are challenged by the last activity in each chapter and assignments in the Projects
section at the end of each chapter. Independent learners can work at their own pace, and
obtain assistance through the Stamps in Class forum cited below.
Stamps In Class Group: Open to students, educators, and independent learners, this forum
allows members to ask each other questions and share answers as they work through the
activities, exercises and projects in this text.
Parallax Educator’s Group: the Teacher’s Guide for this text is available only to
educators; it may be obtained through this forum after proof of status as an educator has
been verified by Parallax. This moderated forum provides support for educators and
welcomes feedback as we continue to develop our Stamps in Class curriculum.
These groups are accessible from www.parallax.com under Discussion Groups on the
Support menu. If you are having difficulty subscribing to either of these Yahoo! Groups,
Page vi · What’s a Microcontroller?
or have other questions about this text or Stamps in Class, contact the Parallax Stamps in
Class Team directly at stampsinclass@parallax.com.
“Advanced Robotics: with the Toddler”, Student Guide, Version 1.2, Parallax
Inc., 2003
“SumoBot”, Student Guide, Version 1.1, Parallax Inc., 2002
“Elements of Digital Logic”, Student Guide, Version 1.0, Parallax Inc., 2003
“StampWorks”, Manual, Version 1.2, Parallax Inc., 2001
“Understanding Signals”, Student Guide, Version 1.0, Parallax Inc., 2003
Reference
This book is an essential reference for all Stamps in Class Student Guides. It is packed
with information on the BASIC Stamp microcontrollers, the Board of Education and our
other carrier boards, our BASIC Stamp Editor, and our PBASIC programming language.
“BASIC Stamp Manual”, Users Manual, Version 2.0c, Parallax Inc., 2000
CONDITIONS OF DUPLICATION
Parallax 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.
FOREIGN TRANSLATIONS
Parallax educational texts may be translated to other languages with our permission (e-
mail stampsinclass@parallax.com). If you plan on doing any translations please contact
us so we can provide the correctly-formatted MS Word documents, images, etc. We also
maintain a discussion group for Parallax translators that you may join. It’s called the
Parallax Translators Yahoo-group, and directions for finding it are included on the inside
cover of this text. See section entitled: WEB SITE AND DISCUSSION LISTS after the
Title page.
SPECIAL CONTRIBUTORS
The Parallax team assembled to write this text includes: curriculum design and technical
writing by Andy Lindsay, illustration by Rich Allred, cover design by Jen Jacobs and
Larissa Crittenden, general consulting by Aristides Alvarez and Jeff Martin,
electromechanical consulting by John Barrowman, technical review by Kris Magri,
Page viii · What’s a Microcontroller?
technical editing by Stephanie Lindsay, and committee review by Rich Allred, Gabe
Duran, Stephanie Lindsay, and Kris Magri.
What’s a Microcontroller? Student Guide Version 2.1 was written by Andy Lindsay after
collecting observations and educator feedback while traveling the nation teaching
Parallax Educators Courses. Andy studied Electrical and Electronic Engineering at
California State University, Sacramento, and this is his third Stamps in Class Student
Guide. He is also a contributing author of several papers that address the topic of
microcontrollers in pre-engineering curricula. When he’s not writing educational
material, Andy does product engineering for Parallax.
Parallax wishes to thank StampsInClass Yahoo Group member Robert Ang for his
thorough draft review and detailed input, and veteran engineer and esteemed customer
Sid Weaver for his insightful review. Thanks also to Stamps in Class authors Tracy
Allen (Applied Sensors), and Martin Hebel (Industrial Control) for their review and
recommendations. Andy Lindsay wishes to thank his father Marshall and brother-in-law
Kubilay for their expert musical advice and suggestions. Stamps in Class was founded
by Ken Gracey, and Ken wishes to thank the Parallax staff for the great job they do.
Each and every Parallaxian has made contributions to this and every Stamps in Class text.
Chapter #1: Getting Started · Page 1
Figure 1-1
Every-Day Examples of
Devices that Contain
Microcontrollers
Try making a list and counting how many devices with microcontrollers you use in a
typical day. Here are some examples: if your clock radio goes off, and you hit the snooze
button a few times in the morning, the first thing you do in your day is interact with a
microcontroller. Heating up some food in the microwave oven or and making a call on a
cell phone also involves operating microcontrollers. That’s just the beginning. Here are
a few more examples: turning on the television with a handheld remote, playing a
handheld game, using a calculator, and checking your digital wristwatch. All those
devices have microcontrollers inside them that interact with you.
Figure 1-2
The BASIC Stamp 2
In this text, BASIC Stamp is used to refer to the BASIC Stamp 2. There are other BASIC
Stamps, some of which are shown in Figure 1-3. Each BASIC Stamp is color coded. The
BASIC Stamp 2 is green. The BASIC Stamp 2e is red. The BASIC Stamp 2 SX is blue, and
the BASIC Stamp 2p is gold. Each variation on the BASIC Stamp 2 is slightly different,
featuring higher speed, more memory, additional functionality, or some combination of these
extra features.
Figure 1-3
BASIC Stamp
Modules
From Left to
Right: BASIC
Stamp 2, 2e,
2SX, and 2p
Robots have been designed to do everything from helping students learn more about
microcontrollers, to mowing the lawn, to solving complex mechanical problems. Figure
1-4 shows two example robots. On each of these robots, students use the BASIC Stamp
to read sensors, control motors, and communicate with other computers. The robot on
the left is called the Boe-Bot. The projects in the Robotics! text can be tackled using the
Boe-Bot after you’ve worked through the activities in this one. The robot on the right
Chapter #1: Getting Started · Page 3
was built by a group of students and entered into a recent First Robotics competition.
The goal of the contest is different each year. In the example shown, the goal was to see
which group’s robot could sort colored hoops the fastest.
Figure 1-4
Educational Robots
Other robots solve complex problems, such as the autonomous remote flight robot shown
at the left of Figure 1-5. This robot was built and tested by mechanical engineering
students at the University of California, Irvine. They used a BASIC Stamp to help it
communicate with a satellite global positioning system (GPS) so that the robot could
know its position and altitude. The BASIC Stamp also read level sensors and controlled
the motor settings to keep the robot flying properly. The mechanical millipede robot on
the right was developed by a professor at Nanyang Technical University, Singapore. It
has more than 50 BASIC Stamps, and they all communicate with each other in an
elaborate network that helped control and orchestrate the motion of each set of legs.
Robots like this not only help us better understand designs in nature, but they may
eventually be used to explore remote locations, or even other planets.
Figure 1-5
Examples of Research
Robots that Contain
Microcontrollers
Autonomous flying
robot at UC, Irvine (left)
and Millipede Project at
Nanyang University
(right)
With the help of microcontrollers, robots will also take on day-to-day tasks, such as
mowing the lawn. The BASIC Stamp inside the robotic lawn mower shown in Figure 1-6
Page 4 · What’s a Microcontroller?
helps it stay inside the boundaries of the lawn, and it also reads sensors that detect
obstacles and controls the motors that make it move.
Figure 1-6
Robotic Lawn Mower
Microcontrollers are also used in scientific, high technology, and aerospace projects.
The weather station shown on the left of Figure 1-7 is used to collect environmental data
related to coral reef decay. The BASIC Stamp inside it gathers this data from a variety of
sensors and stores it for later retrieval by scientists. The submarine in the center is an
undersea exploration vehicle, and its thrusters, cameras and lights are all controlled by
BASIC Stamps. The rocket shown on the right is one that was part of a competition to
launch a privately owned rocket into space. Nobody won the competition, but this rocket
almost made it because it was launched from a platform raised to high altitudes by
weather balloons. The BASIC Stamp controlled just about every aspect of the launch
sequence by sensing altitude, communicating information to ground based technicians,
and triggering the actual launch.
Figure 1-7
High-tech and Aerospace
Microcontroller Examples
From common household appliances all the way through scientific and aerospace
applications, the microcontroller basics you will need to get started on projects like these
are introduced here. By working through the activities in this book, you will get to
Chapter #1: Getting Started · Page 5
experiment with and learn how to use a variety of building blocks found in all these cool
gizmos. You will build circuits for displays, sensors, and motion controllers. You will
learn how to connect these circuits to the BASIC Stamp, and then write computer
programs that make it control displays, collect data from the sensors, and control motion.
Along the way, you will learn many important electronic and computer programming
concepts and techniques. By the time you’re done, you might find yourself well on the
way to inventing a gizmo of your own design.
The BASIC Stamp Editor is free software, and the two easiest ways to get it are:
x Download from the Internet: Look for “BASIC Stamp Windows Editor version
2.0…” on the www.parallax.com ĺ Downloads ĺ BASIC Stamp Software page.
x Included on the Parallax CD: Follow the Software link on the Welcome page.
Make sure the date printed on the CD is May 2003 or newer.
In a Hurry? Get your copy of the BASIC Stamp Windows Editor version 2.0 (or higher) and
install it on your PC or laptop. Then, skip to: Activity #3: Setting Up the Hardware and
Testing the System.
If you have questions along the way, Activity #1 can be used as a step-by-step reference
for getting the software, and Activity #2 can be used as a reference for the installation
procedure.
Page 6 · What’s a Microcontroller?
USB Port Adaptor If your computer only has USB ports, you will need a USB to Serial
Adaptor. See Appendix A: USB to Serial Adaptor for details and installation instructions.
Figure 1-8
The Parallax Web Site:
www.parallax.com
Chapter #1: Getting Started · Page 7
When you get to the BASIC Stamp Software page, find the most recent version
of the BASIC Stamp Windows Editor download, with a version number of 2.0 or
higher.
Click the Download icon. In Figure 1-9, the download icon looks like a file
folder to the right of the description: “BASIC Stamp Windows Editor version 2.0
Beta 1 (6MB)”.
Figure 1-9
The Parallax Web Site
Downloads Page
When the File Download window shown in Figure 1-10 appears, select: Save
this program to disk.
Click the OK button.
Figure 1-10
File Download Window
Figure 1-11 shows the Save As window that appears next. You can use the Save in field
to browse your computer’s hard drives to find a convenient place to save the file.
After choosing where to save the file you are downloading, click the Save
Button.
Page 8 · What’s a Microcontroller?
Figure 1-11
Save As Window
Selecting a place to
save the file
Wait while the BASIC Stamp Editor installation program downloads (shown in
Figure 1-12). This may take a while if you are using a modem connection.
Figure 1-12
Download Progress
Window
When the download is complete, leave the window shown in Figure 1-13 open
while you skip to the next section - Activity #2: Installing the Software.
Figure 1-13
Download Complete
Place the Parallax CD into your computer’s CD drive. The Parallax CD browser
is called the Welcome application. It’s shown in Figure 1-14 and it should run as
soon as you load the CD into your computer’s CD drive.
If the Welcome application does not automatically run, double-click My
Computer, then double-click your CD drive, then double-click Welcome.
Click the Software link shown in Figure 1-14.
Figure 1-14
The Parallax CD
Browser
Click the + next to the BASIC Stamps folder shown in Figure 1-15.
Click the + next to the Windows folder.
Page 10 · What’s a Microcontroller?
Figure 1-15
The Parallax CD
Browser
Free downloads at the Parallax web site are included in the Parallax CD, but only up to the
date the CD was created. The date on the front of the CD indicates when it was created. If
the CD is just a few months old, you will probably have the most up-to-date material. If it’s
an older CD, consider requesting a new one from Parallax or downloading the files you need
from the Parallax web site.
If you downloaded the BASIC Stamp Editor Installer from the Internet, click the
Open Folder button on the Download Complete window shown in Figure 1-16.
Chapter #1: Getting Started · Page 11
Figure 1-16
Download Complete Window
If you located the software on the Parallax CD, click the Install button shown in
Figure 1-17.
Figure 1-17
The Parallax CD Browser
When the BASIC Stamp Editor’s InstallShield Wizard window opens, click the
Next button shown in Figure 1-18.
Figure 1-18
InstallShield Wizard for
the BASIC Stamp Editor
Click Next.
Figure 1-19
Setup Type
When the InstallShield Wizard tells you it is “Ready to Install the Program”,
click the Install button shown in Figure 1-20.
Figure 1-20
Ready to Install.
Figure 1-21
InstallShield Wizard
Completed:
Figure 1-22
BASIC Stamp 2
(left) and Board
of Education
(right)
Page 14 · What’s a Microcontroller?
The BASIC Stamp HomeWork Board is shown in Figure 1-23. This board is like a
Board of Education with the BASIC Stamp 2 built-in. You can use either the Board of
Education or the BASIC Stamp HomeWork Board for the activities in this text.
Figure 1-23
BASIC Stamp
HomeWork
Board
Learn more about the features parts and functions of the BASIC Stamp, Board of
Education, and HomeWork Board. See Appendix C: BASIC Stamp and Carrier Board
Components and Functions on page 299.
Required Hardware
(1) BASIC Stamp 2 and (1) Board of Education
- or -
(1) BASIC Stamp HomeWork Board
Figure 1-24
9 V Battery,
Rubber Feet,
and Serial
Cable
Start with a new or fully charged 9 V battery. Avoid all the confusion a dead battery can
cause. Start with a new alkaline battery or a rechargeable battery that has recently been
fully recharged.
CAUTION
Before using an AC adaptor, “battery replacer”, or DC supply:
¥ Consult Appendix D: Batteries and Power Supplies on page 303 to make sure the
supply you use is appropriate for the activities in this text.
Figure 1-25
Rubber Feet
If you are using the Board of Education, it has circles on its underside that show
where each rubber foot should be attached. Remove each rubber foot from the
adhesive strip and affix it to the underside of the Board of Education as shown in
Figure 1-26.
Page 16 · What’s a Microcontroller?
Figure 1-26
Rubber Foot
Affixed to
Underside of
Board of
Education
If you are using the BASIC Stamp HomeWork Board, remove each rubber foot
from its adhesive strip and affix it to the underside of the HomeWork Board,
next to each a plated hole at each corner of the board as shown in Figure 1-27.
Figure 1-27
Rubber Foot
Affixed to
Underside of
HomeWork
Board
Next, the Board of Education or BASIC Stamp HomeWork Board should be connected to
your PC or laptop by a serial cable.
Connect your serial cable to an available COM port on the back of your
computer as shown in Figure 1-28.
Com
Figure 1-28
PC or Laptop COM Port
Figure 1-29
Reset 3-position Switch
0 1 2
Set to the 0 position to
turn off the power.
Only the Board of Education Rev C has a 3-position switch. To turn off power on a Board
of Education Rev B, simply disconnect the power source by either unplugging the DC supply
or the battery These are shown in Figure 1-30, step 3 or 4.
If your BASIC Stamp is not already plugged into your Board of Education, insert
it into the socket shown in Figure 1-30, step-1. Make sure the pins are lined up
properly with the holes in the socket, then press down firmly.
Plug the serial cable into the Board of Education as shown in step-2.
Plug a DC power supply into the 6-9 VDC jack as shown in step-3, or plug a 9-V
battery into the 9 VDC battery jack as shown in step-4.
Move the 3-position switch from position-0 to position-1.
The green light labeled Pwr on the Board of Education should now be on.
Page 18 · What’s a Microcontroller?
Powercell
Alkaline Battery
3 or 4
Figure 1-30
6-9VDC 15 14 Vdd 13 12
Board of
9 Vdc
Battery Red
Black
Education,
Pwr
X4 X5 BASIC Stamp,
Vdd Vin Vss
STA
Vss Vss X3 Battery and
P0 P1
in MPS
C LA
SS P2
P4
P3
P5
P15
P14
Serial Cable.
P6 P7 P13
TM P12
P8 P9
1 P11
Sout
Sin
Vin
Vss
P10
P12
P11
P13 P10
P9
Connect
P14 P15
ATN
Vss
Rst
Vdd
Vdd
X1
Vin P8
P7 components in
P0
P1
P2
U1
P15
P14
P13
P6
P5 the order
P4
P3
P4
P12
P11 Reset
P3
P2
shown in the
P5
P6
P10
P9
P1
P0 diagram.
P7 P8 X2
0 1 2 Board of Education
2 www.stampsinclass.com © 2000-2003
Connect the serial cable to the HomeWork Board as shown in Figure 1-31, step-
1.
Connect a 9 V battery to the battery clip as shown in step-2.
Chapter #1: Getting Started · Page 19
Figure 1-31
1 HomeWork Board and
Serial Cable
STA
in MPS
CL A
SS
(916) 624-8333
www.parallaxinc.com Rev A
Plug the serial cable
and 9 V battery into the
www.stampsinclass.com
Vdd Vin Vss
X3
HomeWork Board.
P15
P14
P13
2 P12
P11
P10
P9
P8
P7
P6
P5
P4
Power P3
P2
P1
Alkaline Battery
Powercell
P0
X2
Reset
© 2002
£
BASIC Stamp HomeWork Board
Double-click the BASIC Stamp Editor shortcut on your desktop. It should look
similar to the one shown in Figure 1-32.
Figure 1-32
BASIC Stamp Editor Shortcut
The Windows Start Menu can also be used to run the BASIC Stamp Editor. Click your
Windows Start button, then select Programs ĺ Parallax, Inc. ĺ Stamp Editor 2…, then click
the BASIC Stamp Editor icon.
Your BASIC Stamp Editor window should look similar to the one shown in Figure 1-33.
The first time you run your BASIC Stamp Editor, it may display some messages and a
list of your COM ports found by the software.
To make sure your BASIC Stamp is communicating with your computer, click
the Run menu, then select Identify.
Figure 1-33
BASIC Stamp
Editor
Select Identify
from the Run
menu.
An Identification window similar to the one shown in Figure 1-34 will appear. The
example in the figure shows that a BASIC Stamp 2 has been detected on COM2.
Check the Identification window to make sure a BASIC Stamp 2 has been
detected on one of the COM ports. If the BASIC Stamp 2 has been detected,
then you are ready for Activity #4: First Program.
If the Identification window does not detect a BASIC Stamp 2 on any of the
COM ports, go to Appendix E: Trouble-Shooting.
Figure 1-34
Identification Window
10
01
1 0 0 0 01 0 0
100
11 Figure 1-35
Messages from the
00 0
Powercell
0
10
1
10101001
Alkaline Battery
0
BASIC Stamp to Your
Computer
10
6-9VDC
10 your PC or laptop by
01 transmitting a stream
0 010
000
1 001 STAM
PS of binary ones and
11
in
CLASS
0 TM
zeros. The BASIC
Stamp Editor can
101
1
Sout Vin
Sin
ATN
Vss
Rst detect and convert
these binary codes to
1
Vss Vdd
0 P0 P15
P1 P14
10 P2
U1
P13
characters and display
P3 P12
P4
P5
P11
P10 them.
P6 P9
P7 P8
www.stampsinclass.com
First Program
The program listings that you will type into the BASIC Stamp Editor and download to
the BASIC Stamp will always be shown with a gray background. Here is an example:
END
Type this program into the BASIC Stamp Editor as shown in Figure 1-36.
Figure 1-36
First Program
Entered into
Editor
Save your work by clicking File and selecting Save, (shown in Figure 1-37).
Figure 1-37
Saving the First
Program
Enter the name FirstProgram into the File name field near the bottom of the Save
As window as shown in Figure 1-38.
Click the Save button.
Figure 1-38
Entering the File Name
Chapter #1: Getting Started · Page 23
The next time you save, the BASIC Stamp Editor will automatically save to the same
filename (FirstProgram.bs2) unless you tell it to save to a different filename by clicking File
and selecting Save As (instead of just Save).
Click Run, and select Run from the menu that appears (by clicking it) as shown
in Figure 1-39.
Figure 1-39
Running Your First
Program
A Download Progress window will appear briefly as the program is transmitted from the
PC or laptop to your BASIC Stamp. Figure 1-40 shows the Debug Terminal that should
appear when the download is complete. You can prove to yourself that this is a message
from the BASIC Stamp by pressing and releasing the button labeled Rst (Board of
Education) or Reset (HomeWork Board). This button is called the reset button. Every
time you press and release it, the program will re-run, and you will see another copy of
the message displayed in the Debug Terminal.
Press and release the reset button. Did you see a second “Hello…” message
appear in the Debug Terminal?
Figure 1-40
Debug Terminal
The BASIC Stamp Editor has shortcuts for most common tasks. For example, to run a
program, you can press the ‘Ctrl’ and ‘R’ keys at the same time. You can also click the Run
button. It’s the blue triangle shown in Figure 1-41 that looks like a CD player’s Play button.
The flyover help (the Run hint) will appear if you point at the Run button with your mouse.
You can get similar hints to find out what the other buttons do by pointing at them too.
Figure 1-41
BASIC Stamp Editor
Shortcut Buttons
Although comments are ignored most of the time, the BASIC Stamp Editor does search
through comments for special directives. Every program in this text will use these two
directives:
' {$STAMP BS2}
' {$PBASIC 2.5}
The first directive is called the Stamp Directive, and it tells the BASIC Stamp Editor that
you will be downloading the program to a BASIC Stamp 2. The second directive is
called the PBASIC directive, and it tells the BASIC Stamp Editor that you are using
version 2.5 of the PBASIC programming language.
A command is a word you can use to tell the BASIC Stamp do a certain job. The first of
the two commands in this program is called the DEBUG command:
DEBUG "Hello, it's me, your BASIC Stamp!"
Chapter #1: Getting Started · Page 25
This is the command that tells the BASIC Stamp to send a message to the PC using the
serial cable.
This command is handy because it puts the BASIC Stamp into low power mode when it’s
done running the program. In low power mode, the BASIC Stamp waits for either the
reset button to be pressed (and released), or for a new program to be loaded into it by the
BASIC Stamp Editor. If the reset button on your board is pressed, the BASIC Stamp will
re-run the program you loaded into it. If a new program is loaded into it, the old one is
erased, and the new program begins to run.
First, save the program under a new name by clicking File and selecting Save As.
A good new name for the file would be FirstProgramYourTurn.bs2
Modify the comments at the beginning of the program so that they read:
' What's a Microcontroller - FirstProgramYourTurn.bs2
' BASIC Stamp sends messages to Debug Terminal.
Add these three lines between the first DEBUG command and the END command:
DEBUG CR, "What's 7 X 11?"
DEBUG CR, "The answer is: "
DEBUG DEC 7 * 11
Save the changes you made by clicking File and selecting Save.
Your program should now look like the one shown in Figure 1-42.
Page 26 · What’s a Microcontroller?
Run your modified program. Hint: you will have to either click Run from the
Run menu again, like in Figure 1-39 or click the Run button, like in Figure 1-41.
Figure 1-42
Modified
FirstProgram
Where did my Debug Terminal go? Sometimes the Debug Terminal gets hidden behind
the BASIC Stamp Editor window. You can bring it back to the front by using the Run menu
as shown at the left of Figure 1-43, the Debug Terminal 1 shortcut button shown at the right
of the figure, or the F12 key on your keyboard.
Figure 1-43
Debug Terminal 1 to
Foreground
Using the menu (left)
and using the shortcut
button (right).
Figure 1-44
Modified
FirstProgram.bs2
Debug Terminal Output
In the BASIC Stamp Editor, Click Help, then select Index as shown in Figure 1-
45.
Figure 1-45
Selecting Index
from the Help
Menu
Type DEBUG into the field labeled Type in the keyword to find: (shown in
Figure 1-46).
When the word DEBUG appears in the list below where you are typing, click it,
then click the Display button.
Page 28 · What’s a Microcontroller?
Figure 1-46
Looking up
the DEBUG
Command
Using Help.
Your Turn
Use the scrollbar to review the DEBUG command’s write-up. Notice that it has
lots of explanations and example programs you can try.
Click the Contents tab, and find DEBUG there.
Click the Search tab, and run a search for the word DEBUG.
Repeat this process for the END command.
Downloading the BASIC Stamp Manual from the Parallax Web Site
Figure 1-47 shows an excerpt from the BASIC Stamp Manual v2.0 Contents
section. It shows that information on the DEBUG command can be found on page
97.
Figure 1-47
Finding the
DEBUG
Command in
the Table of
Contents
Figure 1-48 shows an excerpt from page 97 in the BASIC Stamp Manual v2.0. The
DEBUG command is explained in detail here along with example programs to demonstrate
how the DEBUG command can be used.
Briefly look over the BASIC Stamp Manual’s explanation of the DEBUG
command.
Page 30 · What’s a Microcontroller?
Count the number of example programs in the DEBUG section. How many are
there?
Figure 1-48
Reviewing
the DEBUG
Command
in the
BASIC
Stamp
Manual
Your Turn
Use the BASIC Stamp Manual’s Index to look up the DEBUG command.
Look up the END command in the BASIC Stamp Manual.
Circuit prototypes should never be left unattended with a battery or power supply
connected. You never know what kind of accident might occur when you are not there.
Always disconnect the power from your Board of Education or HomeWork Board, even if
you only plan on leaving it alone for a minute or two.
If you are in a classroom, your instructor may have extra instructions, such as
disconnecting the serial cable, storing your Board of Education or HomeWork Board in a
safe place, etc. Aside from those details, the most important step that you should always
follow is disconnecting power when you’re done.
Chapter #1: Getting Started · Page 31
Disconnecting Power
With the Board of Education Rev C, disconnecting power is easy:
If you are using the Board of Education Rev C, move the 3-position switch to
position-0 by pushing it to the left as shown in Figure 1-49.
P10 P11
Sout Vin P12 P13 P10
Sin Vss P14 P15 P9
ATN Rst Vdd Vin P8
Vss Vdd X1 P7
P0 P15 P6
P1
P2
U1 P14
P13
P5
P4
Figure 1-49
P3
P4
P12
P11 Reset
P3
P2
Turning the Power off
P5 P10 P1
P6 P9 P0
P7 P8 X2
0 1 2 Board of Education Board of Education
www.stampsinclass.com © 2000-2003
Rev C
Do not remove the BASIC Stamp From its socket in the Board of Education. Resist
any temptation to store your Board of Education and BASIC Stamp separately. Every time
the BASIC Stamp is removed and re-inserted into the socket on the Board of Education,
mistakes may occur that can damage it. Although the BASIC Stamp is sometimes moved
from one socket to another during a larger project, it will not be necessary during any of the
activities in this text.
If you are using the BASIC Stamp HomeWork Board, disconnect the battery as
shown in Figure 1-50.
Vdd Vin Vss
X3
P15
P14
P13
P12
P11
P10
P9
P8
Figure 1-50
P7
P6 Disconnecting the
Power
P5
P4
P3
power to the HomeWork
P2
P1
Board
Alkaline Battery
Powercell
P0
X2
Reset
© 2002
The Board of Education Rev B also has to have its power disconnected, either by
removing the battery or by unplugging the DC supply from the jack.
Your Turn
Disconnect the power to your board now.
Chapter #1: Getting Started · Page 33
SUMMARY
This chapter guided you through the following:
Questions
1. What is a microcontroller?
2. Is the BASIC Stamp a microcontroller, or does it contain one?
3. What clues would you look for to figure out whether or not an appliance like a
clock radio or a cell phone contains a microcontroller?
4. What is the purpose of the serial cable?
5. When the BASIC Stamp sends a character to your PC/laptop, what numbers are
used to send the message through the serial cable?
6. What should you do between the time you have entered your program into the
BASIC Stamp Editor and the time you run the program?
7. What is the name of the window that displays messages sent from the BASIC
Stamp to your PC/laptop?
8. What does an apostrophe at the beginning of a line of PBASIC program code
signify?
9. What PBASIC commands did you learn in this chapter?
Page 34 · What’s a Microcontroller?
10. Let’s say you want to take a break from your BASIC Stamp project to go get a
snack, or maybe you want to take a longer break and return to the project in a
couple days. What should you always do before you take your break?
Exercises
1. Explain what you can do with each PBASIC command you learned in this
chapter.
2. Explain what would happen if you took all the CR control characters out of the
DEBUG commands below and write down how it would look in the Debug
Terminal.
DEBUG "Hello, it's me, your BASIC Stamp!"
DEBUG CR, "What's 7 X 11?"
DEBUG CR, "The answer is: "
4. Guess what the Debug Terminal would display if you ran this command:
DEBUG DEC 7 + 11
5. There is a problem with these two commands. When you run the code, the
numbers they display are stuck together so that it looks like one large number
instead of two small ones. Modify these two commands so that the answers
appear on different lines in the Debug Terminal.
DEBUG DEC 7 * 11
DEBUG DEC 7 + 11
Projects
1. Use DEBUG to display the solution to the math problem: 1 + 2 + 3 + 4.
2. Use the Your Turn – DEBUG Formatters section on page 25 as a template for
saving your file under a new name and modifying it. Use the filename
FirstProgramCh01Project02.bs2. Add this line to the program, then run it:
DEBUG 65, 66, 67, 68, 69, 70
Next, insert the DEC formatter before each of these numbers so that the line
reads:
DEBUG DEC 65, DEC 66, DEC 67, DEC 68, DEC 69, DEC 70
Chapter #1: Getting Started · Page 35
Re-run the program and describe what the DEC formatter does. Most
microcontrollers and PC computers adhere to the American Standard Code for
Information Interchange. You’ll usually see it referred to as ASCII code. The
ASCII code for ‘A’ is 65, ‘B’ is 66, ‘C’ is 67, and so on. The ASCII code for a
space character is 32, and the code for a carriage return (CR) is 13. Try this and
explain in a one paragraph report what each of these lines is doing.
DEBUG "Hello!"
DEBUG 32, 32, 32, 32
DEBUG "Hello again!"
DEBUG 13
DEBUG "Goodbye."
3. Predict what you would expect to see if you removed the DEC formatter from this
command. Use a PBASIC program to test your prediction.
DEBUG DEC 7 * 11
4. Take a second look at Figure 1-35 on page 21. How can you send the number 65
(representing an ‘A’) if you are restricted to zeros and ones? The answer is that
the number 65 can be represented using ones and zeros. You will learn more
about the binary (base-2) number system later. For now, just modify a program
by adding this code segment to it and verify that it does the same thing as your
code segment in Project 2.
' Send the ASCII codes 65, 66, 67, 68, 69, and 70.
' Debug terminal will display "ABCDEF".
Further Investigation
In this chapter, you visited the Software section of either the Parallax web site or the
Parallax CD to get a copy of the BASIC Stamp Editor. You can go to the Documentation
Page 36 · What’s a Microcontroller?
sections of either the Parallax web site or the Parallax CD to get a free copy of this text
and of the BASIC Stamp Manual. Printed copies can also be purchased from Parallax.
“BASIC Stamp Manual”, Users Manual, Version 2.0c, Parallax Inc., 2000
You can learn much more about the DEBUG and END commands by looking them
up in the BASIC Stamp Manual. You can find them using the Table of Contents.
The BASIC Stamp Manual has many more examples you can try, along with
lessons similar to those in the Projects section you just completed.
Chapter #2: Lights on – Lights off · Page 37
Figure 2-1
Indicator
Lights
Turning an indicator light on and off is a simple matter of connecting and disconnecting
it from a power source. In some cases, the indicator light is connected directly to the
battery or power supply, like the power indicator light on the Board of Education. Other
indicator lights are switched on and off by a microcontroller inside the device. These are
usually status indicator lights that tell you what the device is up to.
An LED circuit can be connected to the BASIC Stamp, and the BASIC Stamp can be
programmed to connect and disconnect the LED circuit’s power. This is much easier
than manually changing the circuit’s wiring or connecting and disconnecting the battery.
The BASIC Stamp can also be programmed to do the following:
Resistors like the ones we are using in this activity have colored stripes that tell you what
their resistance values are. There is a different color combination for each resistance
value. For example, the color code for the 470 ȍ resistor is yellow-violet-brown.
There may be a fourth stripe that indicates the resistor’s tolerance. Tolerance is measured
in percent, and it tells how far off the part’s true resistance might be from the labeled
resistance. The fourth stripe could be gold (5%), silver (10%) or no stripe (20%). For the
activities in this book, a resistor’s tolerance does not matter, but its value does.
Each color bar that tells you the resistor’s value corresponds to a digit, and these
colors/digits are listed in Table 2-1. Figure 2-3 shows how to use each color bar with the
table to determine the value of a resistor.
Table 2-1:
Resistor Color
Code Values
Digit Color
Tolerance
0 Black Code
1 Brown
Figure 2-3
2 Red Resistor Color
3 Orange Codes
First Digit Number of Zeros
4 Yellow
Second Digit
5 Green
6 Blue
7 Violet
8 Gray
9 White
Here is an example that shows how Table 2-1 and Figure 2-3 can be used to figure out a
resistor value by proving that yellow-violet-brown is really 470 ::
Page 40 · What’s a Microcontroller?
Yellow-Violet-Brown = 4-7-0.
Figure 2-4 shows an LED’s schematic symbol and part drawing. An LED has two
terminals. One is called the anode, and the other is called the cathode. In this activity,
you will have to build the LED into a circuit, and you will have to pay attention and make
sure the leads connected to the anode and cathode are connected to the circuit properly.
On the part drawing, the anode lead is labeled with the plus-sign (+). On the schematic
symbol, the anode is the wide part of the triangle. In the part drawing, the cathode lead is
the unlabeled pin, and on the schematic symbol, the cathode is the line across the point of
the triangle.
Chapter #2: Lights on – Lights off · Page 41
Figure 2-4
LED Part Drawing
and Schematic
Symbol
When you start building your circuit, make sure to check it against the schematic symbol
and part drawing. For the part drawing, note that the LED’s leads are different lengths.
The longer lead is connected to the LED’s anode, and the shorter lead is connected to its
cathode. Also, if you look closely at the LED’s plastic case, it’s mostly round, but there
is a small flat spot right near the shorter lead that that tells you it’s the cathode. This
really comes in handy if the leads have been clipped to the same length.
Identifying the parts: In addition to the part drawings in Figure 2-2 and Figure 2-4, you can
use the photo on the last page of the book to help identify the parts in the kit needed for this
and all other activities. For more information on the parts in this photo, see Appendix B:
Equipment and Parts Lists.
the BASIC Stamp’s input/output pins. The white board with lots of holes in it is called a
solderless breadboard. You will use this breadboard to connect components to each other
and build circuits.
Vdd Vin Vss
X3
P15
P14
P13 Figure 2-5
P12 Prototyping Area
P11
P10
P9 Power terminals (black
P8 sockets along top), I/O pin
P7
P6 access (black sockets along
P5 the side), and solderless
P4
P3 breadboard (white sockets)
P2
P1
P0
X2
Input/output pins are usually called I/O pins, and after connecting your circuit to one or
more of these I/O pins, you can program your BASIC Stamp to monitor the circuit (input) or
send on or off signals to the circuit (output). You will try this in the activity that follows this
one.
Figure 2-6 shows a couple of circuits built on the prototyping area. The breadboard is
separated into rows of five sockets. Each row of five sockets can be used to connect up
to five leads, or wires, to each other. Examples of part leads and wires that are connected
to each other are circled. Although not circled, you can probably tell that one of the
resistor’s leads is connected to P7 and another is connected to P15. One of the LED’s
leads is connected to Vss, and a wire connected to one of the circuits is also connected to
Vss.
Chapter #2: Lights on – Lights off · Page 43
Figure 2-6
X4 X5 Example Circuit on the
+
Vdd Vin Vss Prototyping Area.
X3
P15 DO NOT BUILD THIS
P14 CIRCUIT.
P12
P11 Rows of 5 sockets on
P10
P9 breadboard used to
P8 connect the leads of two
P7
P6 or more parts are
P5 circled. Leads of certain
P4 parts are also
P3
P2 connected to P7, P15,
P1 and Vss.
P0
X2
You are now ready to build the circuit shown in Figure 2-7 (below) by plugging the LED
and resistor leads into sockets on the prototyping area. Follow these steps:
Direction does matter for the LED, but not for the resistor. If you plug the LED in
backward, the LED will not emit light when you connect power. The resistor just resists the
flow of current. There is no backwards or forwards for a resistor.
If your green LED does not emit light when you connect power to the board:
Some LEDs are brightest when viewed from above. Try looking straight down
onto the dome part of the LED’s plastic case from above.
If the room is bright, try turning off some of the lights, or use your hands to cast
a shadow on the LED.
If you still do not see any green glow, try these steps:
Double check to make sure your cathode and anode are connected properly. If
not, simply remove the LED, give it a half-turn, and plug it back in. It will not
hurt the LED if you plug it in backwards, it just doesn’t emit light. When you
have it plugged in the right direction, it should emit light.
Double check to make sure you built your circuit exactly as shown in Figure 2-7.
If you are using a What’s a Microcontroller kit that somebody used before you,
the LED may be damaged, so try a different one.
If you are in a lab class, check with your instructor.
Chapter #2: Lights on – Lights off · Page 45
Still stuck? If you don’t have an instructor or friend who can help, you can always check
with the Stamps in Class discussion group. The first pages of this book has Internet Access
information on where to find the Stamps in Class discussion group. If the group is unable to
help you solve the problem, you can contact the Parallax Technical Support department by
following the Support link at www.parallax.com.
- Figure 2-8
- - LED On Circuit Electron
+ - Flow
N
- -
N N
+++ + + - The minus signs with
+++ = N - - the circles around them
+++
--- - are used to show
- - -N - - electrons flowing from
_
-N - N the battery’s negative
- - terminal to its positive
- terminal.
- - - - -
Chemical reactions inside the battery supply the circuit with current. The battery’s negative
terminal contains a compound that has molecules with extra electrons (shown in Figure 2-8
by minus-signs). The battery’s positive terminal has a chemical compound with molecules
that are missing electrons (shown by plus-signs). When an electron leaves a molecule in
the negative terminal and travels through the wire, it is called a free electron (also shown by
minus-signs). The molecule that lost that extra electron no longer has an extra negative
charge; it is now called neutral (shown by an N). When an electron gets to the positive
terminal, it joins a molecule that was missing an electron, and now that molecule is neutral
too.
Figure 2-9 shows how the flow of electricity through the LED circuit is described using
schematic notation. The electric pressure across the circuit is called voltage. The + and –
signs are used to show the voltage applied to a circuit. The arrow shows the current
Page 46 · What’s a Microcontroller?
flowing through the circuit. This arrow is almost always shown pointing the opposite
direction of the actual flow of electrons. Benjamin Franklin is credited with not having
been aware of electrons when he decided to represent current flow as charge passing from
the positive to negative terminal of a circuit. By the time physicists discovered the true
nature of electric current, the convention was already well established.
Vdd
Voltage + Figure 2-9
LED-On Circuit
Schematic Showing
Resistance Conventional Voltage
and Current Flow
Current
LED The + and – signs show
voltage applied to the
circuit, and the arrow
shows current flow
Voltage - Vss through the circuit.
A schematic drawing (like Figure 2-9) is a picture that explains how one or more circuits
are connected. Schematics are used by students, electronics hobbyists, electricians,
engineers, and just about everybody else who works with circuits.
Appendix F: More About Electricity: This appendix contains some glossary terms and an
activity you can try to get more familiar with measurements of voltage, current and
resistance.
Figure 2-11
SOUT 1 24 VIN SOUT 1 24 VIN BASIC Stamp
SIN
ATN
2
3
BS2
23
22
VSS
RES
SIN
ATN
2
3
BS2
23
22
VSS
RES
Switching
VSS 4 21 VDD (+5V) VSS 4 21 VDD (+5V)
P0 5 Vdd 20 P15 P0 5 Vdd 20 P15
The BASIC
P1 6 19 P14 P1 6 19 P14
P2 7 Vss 18 P13 P2 7 Vss 18 P13 Stamp can be
P3 8 17 P12 P3 8 17 P12 programmed to
P4 P11 P4 P11
internally
9 16 9 16
P5 10 15 P10 P5 10 15 P10
P6 11 14 P9 P6 11 14 P9 connect the
P7 12 13 P8 P7 12 13 P8
LED circuit’s
BS2-IC BS2-IC input to Vdd or
Vss.
There are two big differences between changing the connection manually and having the
BASIC Stamp do it. First, the BASIC Stamp doesn’t have to cut the power when it
Page 48 · What’s a Microcontroller?
changes the LED circuit’s supply from Vdd to Vss. Second, while a human can make
that change several times a minute, the BASIC Stamp can do it thousands of times per
second!
Resistors are essential. Always remember to use a resistor. Without it, too much current
will flow through the circuit, and it could damage any number of parts in your circuit, BASIC
Stamp, or Board of Education or HomeWork Board.
Chapter #2: Lights on – Lights off · Page 49
DO
HIGH 14
PAUSE 500
LOW 14
PAUSE 500
LOOP
The command PAUSE 500 causes the BASIC Stamp to do nothing for ½ a second while
the LED stays on. The number 500 tells the PAUSE command to wait for 500/1000 of a
second. The number that follows PAUSE is called an argument. If you look up PAUSE in
the BASIC Stamp Manual, you will discover that it calls this number the Duration
argument. The name duration was chosen for this argument to show that the PAUSE
command pauses for a certain ‘duration’ of time, in milliseconds.
Page 50 · What’s a Microcontroller?
The command LOW 14 causes the BASIC Stamp to internally connect I/O pin P14 to Vss.
This turns the LED off. Since LOW 14 is followed by another PAUSE 500, the LED stays
off for half a second.
The reason the code repeats itself over and over again is because it is nested between the
PBASIC keywords DO and LOOP. Figure 2-13 shows how a DO…LOOP works. By placing
the code segment that turns the LED on and off with pauses between DO and LOOP, it tells
the BASIC Stamp to execute those four commands over and over again. The result is
that the LED flashes on and off, over and over again. It will keep flashing until you
disconnect power, press and hold the reset button, or until the battery runs out.
DO
HIGH 14 Figure 2-13
DO…LOOP
PAUSE 250
LOW 14 The code between the
keywords DO and
PAUSE 250 LOOP get executed
over and over again.
LOOP
HIGH 14
PAUSE 250
LOW 14
PAUSE 250
LOOP
Chapter #2: Lights on – Lights off · Page 51
Modify the PAUSE command’s Duration arguments so that they are 250, and re-
run the program.
If you want to make the LED blink on and off once every three seconds, with the low
time twice as long as the high time, you can program the PAUSE command after the HIGH
14 command so that it takes one second using PAUSE 1000. The PAUSE command after
the LOW 14 command will have to be PAUSE 2000.
DO
HIGH 14
PAUSE 1000
LOW 14
PAUSE 2000
LOOP
Modify and re-run the program using the code snippet above.
A fun experiment is to see how short you can make the pauses and still see that the LED
is flashing. When the LED is flashing very fast, but it looks like it’s just on, it’s called
persistence of vision. Here is how to test to see what your persistence of vision threshold
is:
Try modifying both of your PAUSE command’s Duration arguments so that they
are 100.
Re-run your program and check for flicker.
Reduce both Duration arguments by 5 and try again.
Keep reducing the Duration arguments until the LED appears to be on all the
time with no flicker. It will be dimmer than normal, but it should not appear to
flicker.
One last thing to try is to create a one-shot LED flasher. When the program runs, the
LED flashes only once. This is a way to look at the functionality of the DO…LOOP. You
can temporarily remove the DO…LOOP from the program by placing an apostrophe to the
left of both the DO and LOOP keywords as shown below.
' DO
HIGH 14
PAUSE 1000
Page 52 · What’s a Microcontroller?
LOW 14
PAUSE 2000
' LOOP
Modify and re-run the program using the code snippet above.
Explain what happened, why did the LED only flash once?
Counting Parts
Same as previous activity
Test Circuit
Use the example circuit shown in Figure 2-12 on page 48.
The FOR…NEXT loop depends on a variable to track how many times the LED has blinked
on and off. A variable is a word of your choosing that is used to store a value. The next
example program uses the word counter to ‘count’ how many times the LED has been
turned on and off.
Chapter #2: Lights on – Lights off · Page 53
Your test circuit from Activity #2 should be built (or rebuilt) and ready to use.
Enter the LedOnOffTenTimes.bs2 code into the BASIC Stamp Editor.
Connect power to your Board of Education or HomeWork Board.
Run the program.
Verify that the LED flashes on and off ten times.
Run the program a second time, and verify that the value of counter shown in
the Debug Terminal accurately tracks how many times the LED blinked. Hint:
instead of clicking Run a second time, you can press and release the reset button
on your Board of Education or HomeWork Board.
FOR counter = 1 TO 10
DEBUG ? counter
HIGH 14
PAUSE 500
LOW 14
PAUSE 500
NEXT
Page 54 · What’s a Microcontroller?
END
tells the BASIC Stamp Editor that your program will use the word counter as a variable
that can store a byte’s worth of information.
What’s a Byte? A byte is enough memory to store a number between 0 and 255. The
BASIC Stamp has four different types of variables, and each can store a different range of
numbers:
The question mark formatter before a variable in a DEBUG command tells the Debug
Terminal to display the name of the variable and its value. This is how the command
DEBUG ? counter
displays both the name and the value of the counter variable in the Debug Terminal.
The FOR…NEXT loop and all the commands inside it are shown below. The statement FOR
counter = 1 to 10 tells the BASIC Stamp that it will have to set the counter variable
to 1, then keep executing commands until it gets to the NEXT statement. When the
BASIC Stamp gets to the NEXT statement, it jumps back to the FOR statement. The FOR
statement adds one to the value of counter. Then, it checks to see if counter is greater
than ten yet. If not, it repeats the process. When the value of counter finally reaches
eleven, the program skips the commands between the FOR and NEXT statements and
moves on to the command that comes after the NEXT statement.
Chapter #2: Lights on – Lights off · Page 55
FOR counter = 1 to 10
DEBUG ? counter, CR
HIGH 14
PAUSE 500
LOW 14
PAUSE 500
NEXT
This command is included just to show what the program does after ten times through the
FOR…NEXT loop. It moves on to the command that comes after the NEXT statement.
How many times did the LED flash? What values displayed in the Debug
Terminal?
Page 56 · What’s a Microcontroller?
In this activity, you will repeat the LED circuit test in Activity #1 for a second LED
circuit. Then you will adjust the example program from Activity #2 to make sure the
LED circuit is properly connected to the BASIC Stamp. After that, you will modify the
example program from Activity #2 to make the LEDs operate in tandem.
Extra Parts
In addition to the parts you used in Activities 1 and 2, you will need these parts:
DO
HIGH 15
PAUSE 500
LOW 15
PAUSE 500
LOOP
DO
HIGH 14
HIGH 15
PAUSE 500
LOW 14
LOW 15
PAUSE 500
LOOP
Run the modified version of FlashBothLeds.bs2 and verify that the LEDs flash
alternately on and off.
Page 60 · What’s a Microcontroller?
Figure 2-16
Bi-color LED in a
Security Device
Figure 2-17
LED- Bi-color LED
Red Green bicolor
1 2 Schematic symbol (left)
and part drawing (right).
2
Chapter #2: Lights on – Lights off · Page 61
The bi-color LED is really just two LEDs in one package. Figure 2-18 shows how you
can apply voltage in one direction and the LED will glow red. By disconnecting the LED
and plugging it back in reversed, the LED will then glow green. As with the other LEDs,
if you connect both terminals of the circuit to Vss, the LED will not emit light.
Vdd Vdd
Figure 2-18
: :
Bi-color LED
and Applied
1 2 Voltage
: 1
Red (left),
green (center)
LED- LED- and no light
Red 2 1 Green
2 (right)
Vdd
1 Vin 2 Vss Vdd
2 Vin 1 Vss
X3 X3 Figure 2-19
P15 P15 Manual bi-
P14 P14 color LED
P13 P13
P12 P12
Test
P11 P11
P10 P10 Bi-color
P9 P9
P8 P8 LED red
P7 P7 (left) and
P6 P6
P5 P5 green
P4 P4 (right).
P3 P3
P2 P2
P1 P1
P0 P0
X2 X2
Controlling a bi-color LED with the BASIC Stamp requires two I/O pins. After you have
manually verified that the bi-color LED works using the manual test, you can connect the
circuit to the BASIC Stamp as shown in Figure 2-20.
Connect the bi-color LED circuit to the BASIC Stamp as shown in Figure 2-20.
1 2
Vdd Vin Vss
X3
P15
P14
P13
P15 P12 Figure 2-20
1 P11 Bi-color LED Connected
P10
P9 to BASIC Stamp
P8
P7
P6
2 P5
P14 P4
: P3
P2
P1
P0
X2
Chapter #2: Lights on – Lights off · Page 63
The lower schematic shows what happens when P15 is set to Vss and P14 is set to Vdd.
The electrical pressure is now reversed. The red LED shuts off and does not allow
current through. Meanwhile, the green LED turns on, and current passes through the
circuit in the opposite direction.
2 Figure 2-21
LOW = Vss P14
Manual bi-color
:
LED Test
Current through
Red LED (above)
LOW = Vss P15 and Green LED
1 (below).
Current
2
HIGH = Vdd P14
:
Figure 2-21 also shows the key to programming the BASIC Stamp to make the bi-color
LED glow two different colors. The upper schematic shows how to make the bi-color
LED red using HIGH 15 and LOW 14. The lower schematic shows how to make the bi-
color LED glow green by using LOW 15 and HIGH 14. To turn the LED off, send low
signals to both P14 and P15 using LOW 15 and LOW 14. In other words, use LOW on both
pins.
Page 64 · What’s a Microcontroller?
The bi-color LED will also turn off if you send high signals to both P14 and P15. Why?
Because the electrical pressure is the same at P14 and P15 regardless of whether you set
both I/O pins high or low.
DO
LOOP
FOR counter = 1 to 50
HIGH 15
LOW 14
PAUSE counter
LOW 15
HIGH 14
PAUSE counter
NEXT
When you are done, your code should look like this:
DO
FOR counter = 1 to 50
HIGH 15
LOW 14
PAUSE counter
LOW 15
HIGH 14
PAUSE counter
NEXT
LOOP
At the beginning of each pass through the FOR…NEXT loop, the PAUSE value (Duration
argument) is only one millisecond. Each time through the FOR…NEXT loop, the pause gets
longer by one millisecond at a time until it gets to 50 milliseconds. The DO…LOOP causes
the FOR…NEXT loop to execute over and over again.
SUMMARY
The BASIC Stamp can be programmed to switch a circuit with a light emitting diode
(LED) indicator light on and off. LED indicators are useful in a variety of places
including many computer monitors, disk drives, and other devices. The LED was
introduced along with a technique to identify its anode and cathode terminals. An LED
circuit must have a resistor to limit the current passing through it. Resistors were
introduced along with one of the more common coding schemes you can use to figure out
a resistor’s value.
The BASIC Stamp switches an LED circuit on and off by internally connecting an I/O
pin to either Vdd or Vss. The HIGH command can be used to make the BASIC Stamp
internally connect one of its I/O pins to Vdd, and the LOW command can be used to
internally connect an I/O pin to Vss. The PAUSE command is used to cause the BASIC
Stamp to not execute commands for an amount of time. This was used to make LEDs
stay on and/or off for certain amounts of time. This amount of time is determined by the
number used in the PAUSE command’s Duration argument.
The DO…LOOP can be used to create an infinite loop. The commands between the DO and
LOOP keywords will execute over and over again. Even though this is called an infinite
loop, the program can still be re-started by disconnecting and reconnecting power or
pressing and releasing the reset button. A new program can also be downloaded to the
BASIC Stamp, and this will erase the program with the infinite loop.
Current direction and voltage polarity were introduced using a bi-color LED. If voltage
is applied across the LED circuit, current will pass through it in one direction, and it
glows a particular color. If the voltage polarity is reversed, current travels through the
circuit in the opposite direction and it glows a different color.
Questions
1. What is the name of this Greek letter: :?
4. Which resistor would allow more current through the circuit, a 470 : resistor or
a 1000 : resistor?
5. What stripes would you look for on a resistor if you were looking for a value of
2000 ȍ?
7. How do you connect two wires using a breadboard? Can you use a breadboard
to connect four wires together?
9. When current is flowing through an LED circuit, are the electrons flowing out of
Vdd or Vss?
10. What do you always have to do before modifying a circuit that you built on a
breadboard?
13. How would you cause the BASIC Stamp to do nothing for an entire minute?
14. If you place three commands between a DO…LOOP loop, how many times will
these commands be executed?
15. What command can you use to control the number of times a group of
commands get executed?
18. What is the smallest variable you can use to count to 10?
Page 68 · What’s a Microcontroller?
21. Is the command LOW 30 reasonable? If yes, why? If no, what’s wrong with it?
22. If a bi-color LED circuit is connected to P5 and P9, what commands do you need
to turn it on? What commands would you use to make it switch color? What
commands would you use to turn it off?
Exercises
1. Draw the schematic of an LED circuit like the one you worked with in Activity
#2, but connect the circuit to P13 instead of P14.
2. Explain how you would modify LedOnOff.bs2 on Page 49 so that it will make
your LED circuit in Exercise 1 flash on and off four times per second.
Projects
1. Make a 10-second countdown using one yellow LED and one bi-color LED.
Make the bi-color LED start out red for 3 seconds. After 3 seconds, change the
bi-color LED to green. When the bi-color LED changes to green, flash the
yellow LED on and off once every second for ten seconds. When the yellow
LED is done flashing, the bi-color LED should switch back to red and stay that
way.
Use 1000 : resistors for this project. The color code for a 1000 :
resistor is brown-black-red. Do not make a bar graph with more than 8
LEDs using 1000 : resistors. If you want to make a bar graph with
more than 8 LEDs, use 2000 : resistors. The color code for 2000 :
resistors is red black red.
Chapter #2: Lights on – Lights off · Page 69
Write a program that starts with all the LEDs off, then the LEDs start to light up,
one at a time with a one second delay between each LED. The LEDs should
light up either from left to right or bottom to top depending on how you have it
wired. Save the program under a different name and make the LEDs in the bar
graph light up 20-times as fast.
3. Make an automatic streetlight timer. Assume that drivers from both north and
south can see the lights made by the green, yellow, and red LED circuits to P13,
P14, and P15. Make another bank of LEDs connected to P3, P4, and P5 that
control east-west traffic.
Write a program that gives the north-south traffic 30 seconds, then a 10 second
yellow, followed by a 40 second red. When the north-south traffic is red, the
east-west traffic should be green for 30 seconds and yellow for ten seconds, then
red for 40 seconds.
Keep in mind that if this is a real traffic controller, you would be responsible for
traffic problems if both red lights stay on for any length of time. If both green
lights are on at the same time, you could cause a car accident!
Further Investigation
The resources listed here are available for free download from the Parallax web site and
are also included on the Parallax CD.
“BASIC Stamp Manual”, Users Manual, Version 2.0c, Parallax Inc., 2000
The BASIC Stamp Manual has more examples you can try and information that
further explains the following commands: HIGH, LOW, PAUSE, the DEBUG ?
formatter, and FOR…NEXT.
“Basic Analog and Digital”, Student Guide, Version 2.0, Parallax Inc., 2003
Basic Analog and Digital uses LEDs to describe counting in binary, describes
analog conditions, and it introduces new ways to adjust an LED’s brightness.
Page 70 · What’s a Microcontroller?
“BASIC Stamp Editor Help File”, PBASIC 2.5 Version 2.0 Parallax Inc., 2003
The PBASIC 2.5 Help File has information on DO…LOOP, which is new to
PBASIC 2.5 and not included in the BASIC Stamp Manual. You can find this
information by clicking the book icon on your BASIC Stamp Editor task bar,
then selecting PBASIC Reference from the menu in the left sidebar window.
This will open the PBASIC Command Reference alphabetical listing in the main
window. Detailed information can be found by clicking on each command.
Chapter #3: Digital Input - Pushbuttons · Page 71
Other terms that mean send, high/low, and receive: Sending high/low signals is
described in different ways. You may see sending referred to as transmitting, controlling, or
switching. Instead of high/low, you might see it referred to as binary, TTL, CMOS, or
Boolean signals. Another term for receiving is sensing.
have two pins is because it needs stability. If the pushbutton only had two pins, those
pins would eventually bend and break from all the pressure that the pushbutton receives
when people press it.
Figure 3-1
Normally Open
1, 4
1 4 Pushbutton
2, 3 2 3
Schematic symbol (left)
and part drawing (right)
The left side of Figure 3-2 shows how a normally open pushbutton looks when it’s not
pressed. When the button is not pressed, there is a gap between the 1,4 and 2,3 terminals.
This gap makes it so that the 1,4 terminal can not conduct current to the 2,3 terminal.
This is called an open circuit. The name “normally open” means that the pushbutton’s
normal state (not pressed) forms an open circuit. When the button is pressed, the gap
between the 1,4 and 2,3 terminals is bridged by a conductive metal. This is called closed,
and current can flow through the pushbutton.
Figure 3-2
Normally Open
1, 4 1, 4
Pushbutton
2, 3 2, 3
Not pressed (left) and
pressed (right)
Always disconnect power from your Board of Education or BASIC Stamp HomeWork
Board before making any changes to your test circuit. From here onward, the instructions
will no longer say “Disconnect power…” between each circuit modification. It is up to you to
remember to do this.
Always reconnect power to your Board of Education or BASIC Stamp HomeWork Board
before downloading a program to the BASIC Stamp.
Vdd
Warning signs: If the Pwr LED on the Board of Education flickers, goes dim, or goes out
completely when you plug the power supply back in, it means you have a short circuit. If
this happens to you, disconnect power immediately and find and correct the mistake in your
circuit.
The Power LED on the HomeWork Board is different. It glows only while a program is
running. If a program ends (using the END command), the Power LED will also turn off.
Press and hold the pushbutton, and verify that the LED emits light while you are
holding the pushbutton down.
Vdd Vdd
1, 4 1, 4
Figure 3-4
2, 3 2, 3 Pushbutton Not
Pressed, and
Pressed
No 470 : 470 :
Current Current
Pushbutton circuit
open (left) and
LED LED closed (right)
Vss Vss
P15
1, 4 P14
P13
P12
P11 + Figure 3-5
LED P10 LED that Gets
P9
P8 Shorted by
2, 3
P7 Pushbutton
P6
P5
470 : P4
P3
P2
P1
P0
Vss X2
Can you really do that with the LED? Up until now, the LED’s cathode has always been
connected to Vss. Now, the LED is in a different place in the circuit, with its anode
connected to Vdd. People often ask if this breaks any circuit rules, and the answer is no.
The electrical pressure supplied by Vdd and Vss is 5 volts. The diode will always use 1.6
volts, and the resistor will always use 3.4 volts, regardless of their order.
Figure 3-7 shows what the BASIC Stamp sees when the button is pressed, and when it’s
not pressed. When the pushbutton is pressed, the BASIC Stamp senses that Vdd is
connected to P3. Inside the BASIC Stamp, this causes it to place the number 1 in a part
of its memory that stores information about its I/O pins. When the pushbutton is not
pressed, the BASIC Stamp cannot sense Vdd, but it can sense Vss through the 10 k: and
220 : resistors. This causes it to store the number 0 in that same memory location that
stored a 1 when the pushbutton was pressed.
Chapter #3: Digital Input - Pushbuttons · Page 77
7 1
19
18
P14
P13
(below).
P3 8 17 P12
P4 9 0 16 P11
220 : P5 10 15 P10
10 k: P6 11 14 P9
P7 12 13 P8
BS2-IC
Vss
Binary and Circuits: The base-2 number system uses only the digits 1 and 0 to make
numbers, and these binary values can be transmitted from one device to another. The
BASIC Stamp interprets Vdd (5 V) as binary-1 and Vss (0 V) as binary-0. Likewise, when
the BASIC Stamp sets an I/O pin to Vdd using HIGH, it sends a binary-1. When it sets an
I/O pin to Vss using LOW, it sends a binary-0. This is a very common way of communicating
binary numbers used by many computer chips and other devices.
the number 1, and when the pushbutton is not pressed, the Debug Terminal displays the
number 0.
Figure 3-8
Debug Terminal
Displaying
Pushbutton States
DO
DEBUG ? IN3
PAUSE 250
LOOP
The 220 : resistor is used in the pushbutton example circuits to protect the BASIC Stamp
I/O pin. Although it’s a good practice for prototyping, in most products, this resistor is
replaced with a wire (since wires cost less than resistors).
Active-low vs. Active-high: This pushbutton Figure 3-9 is called active-low because it
sends the BASIC Stamp a low signal (Vss) when the button is active (pressed). The
pushbutton circuit in Figure 3-6 the main activity is active-high because it sends a high
signal (Vdd) when the button is active (pressed).
Page 80 · What’s a Microcontroller?
Figure 3-10
Button and LED on
a Computer Monitor
The BASIC Stamp can be programmed to make decisions based on what it senses. For
example, it can be programmed to decide to flash the LED on/off ten times per second
when the button is pressed.
P14
470 :
LED Vdd Vin Vss
X3
+
Vss P15
P14
P13
Vdd P12 Figure 3-11
P11
P10 Pushbutton and
P9 LED Circuit
P8
P7
P3 P6
P5
220 : P4
10 k: P3
P2
P1
P0
Vss X2
DO
Page 82 · What’s a Microcontroller?
DEBUG ? IN3
IF (IN3 = 1) THEN
HIGH 14
PAUSE 50
LOW 14
PAUSE 50
ELSE
PAUSE 100
ENDIF
LOOP
You can make a detailed list of what a program should do, to either help you plan the
program or to describe what it does. This kind of list is called pseudo code, and the
example below uses pseudo code to describe how PushbuttonControlledLed.bs2 works.
x Do the commands between here and the Loop statement over and over again
o Display the value of IN3 in the Debug Terminal
o If the value of IN3 is 1, Then
Turn the LED on
Wait for 1/20 of a second
Turn the LED off
Wait for 1/20 of a second
o Else, (if the value of IN3 is 0)
do nothing, but wait for the same amount of time it would have
taken to briefly flash the LED (1/10 of a second).
x Loop
Chapter #3: Digital Input - Pushbuttons · Page 83
Build the circuit shown in Figure 3-12. If you need help building the circuit
shown in the schematic, use the wiring diagram in Figure 3-13 as a guide.
Modify ReadPushbuttonState.bs2 so that it reads IN4 instead of IN3, and use it
to test your second pushbutton circuit.
Page 84 · What’s a Microcontroller?
P15
470 :
P14
470 :
LED LED
Vss Vss
Figure 3-12
Vdd Vdd
Schematic: Two
Pushbuttons and
LEDs
P4
220 :
P3
220 :
10 k: 10 k:
Vss Vss
Connecting wires with dots: There are three places where wires intersect in Figure 3-12,
but only two dots. Wires only connect if there is a dot at the intersection. The wire that
connects the P4 pushbutton to the 10 k: resistor does not connect to the P3 pushbutton
circuit because there is no dot.
Chapter #3: Digital Input - Pushbuttons · Page 85
DO
Page 86 · What’s a Microcontroller?
DEBUG HOME
DEBUG ? IN4
DEBUG ? IN3
IF (IN3 = 1) THEN
HIGH 14
PAUSE 50
ELSE
PAUSE 50
ENDIF
LOW 14
LOW 15
PAUSE 50
LOOP
By sending the cursor to the home position each time through the DO…LOOP, the
commands:
DEBUG ? IN4
DEBUG ? IN3
display the values of IN4 and IN3 in the same part of the Debug Terminal each time.
These commands in the IF statement are the same as the ones in the example program
from the previous activity:
IF (IN3 = 1) THEN
HIGH 14
Chapter #3: Digital Input - Pushbuttons · Page 87
PAUSE 50
This is where the ELSEIF keyword helps. If IN3 is not 1, but IN4 is 1, we want to turn
the LED connected to P15 on instead of the one connected to P14.
ELSEIF (IN4 = 1) THEN
HIGH 15
PAUSE 50
If neither statement is true, we still want to pause for 50 ms without changing the state of
any LED circuits.
ELSE
PAUSE 50
When you’re finished with all the decisions, don’t forget the ENDIF.
ENDIF
It’s time to turn the LEDs off and pause again. You could try to decide which LED you
turned on and turn it back off. PBASIC commands execute pretty quickly, so why not
just turn them both off and forget about more decision making?
LOW 14
LOW 15
PAUSE 50
The LOOP statement sends the program back up to the DO statement, and the process of
checking the pushbuttons and changing the states of the LEDs starts all over again.
LOOP
HIGH 14
PAUSE 50
A code block is a group of commands. The IF statement above has a code block with
three commands (HIGH, HIGH, and PAUSE). The ELSEIF statement has a code block
with two commands (HIGH, PAUSE).
Run your modified program and see if it handles both pushbutton and LED
circuits as you would expect.
The AND keyword can be used in an IF…THEN statement to check if more than one
condition is true. All conditions with AND have to be true for the IF statement to be true.
The OR keyword can also be used to check if at least one of the conditions are true.
You can also modify the program so that the LED that’s flashing stays on for different
amounts of time. For example, you can reduce the Duration of the PAUSE for both
pushbuttons to 10, increase the PAUSE for the P14 LED to 100, and increase the PAUSE
for the P15 LED to 200.
Modify the PAUSE commands in the IF and the two ELSEIF statements as
discussed.
Run the modified program.
Observe the difference in the behavior of each light.
next hand held game controller. Your next task is to develop a proof of concept for the
reaction timer test.
The solution you will build and test in this activity is an example of how to solve this
problem, but it’s definitely not the only solution. Before continuing, take a moment to
think about how you would design this reaction timer.
P15
1
1 2
Vdd Vin Vss
X3
2
P14 P15
: P14
P13
P12 Figure 3-14
Vdd P11 Reaction
P10
P9 Timer Circuit
P8
P7
P6
P3 P5
P4
220 : P3
10 k: P2
P1
P0
X2
Vss
The example program also demonstrates how polling and counting work. Polling is the
process of checking something over and over again very quickly to see if it has changed.
Counting is the process of adding a number to a variable each time something does (or
does not) happen. In this program, the BASIC Stamp will poll from the time the bi-color
LED turns green until the pushbutton is released. It will wait 1/1000 of a second by using
the command PAUSE 1. Each time it polls and the pushbutton is not yet released, it will
add 1 to the counting variable named timeCounter. When the pushbutton is released,
the program stops polling and sends a message to the Debug Terminal that displays the
value of the timeCounter variable.
Figure 3-15
Debug Terminal
Reaction Timer Game
Instructions
DEBUG "Press and hold pushbutton.", CR, ' Display reaction instructions.
"to make light turn red.", CR, CR,
"When light turns green, let", CR,
"go as fast as you can.", CR, CR
PAUSE 1
timeCounter = timeCounter + 1
DEBUG "Your time was ", DEC timeCounter, ' Display time measurement.
" ms.", CR, CR,
"To play again, hold the ", CR, ' Play again instructions.
"button down again.", CR, CR
The DEBUG commands contain instructions for the player of the game.
DEBUG "Press and hold pushbutton.", CR,
"to make light turn red.", CR, CR,
"When light turns green, let", CR,
"go as fast as you can.", CR, CR
DO…LOOP statements can be nested. In other words, you can put one DO…LOOP inside
another.
DO ' Begin main loop.
The inner DO…LOOP deserves a closer look. A DO…LOOP can use a condition to decide
whether or not to break out of the loop and move on to more commands that come
afterwards. This DO…LOOP will repeat itself as long as the button is not pressed (IN3 =
0). The DO…LOOP will execute over and over again, until IN3 = 1. Then, the program
moves on to the next command after the LOOP UNTIL statement. This is an example of
polling. The DO…LOOP UNTIL polls until the pushbutton is pressed.
DO ' Nested loop repeats...
LOOP UNTIL IN3 = 1 ' until pushbutton press.
The commands that come immediately after the LOOP UNTIL statement turn the bi-color
LED red, delay for one second, then turn it green.
LOW 14 ' Bi-color LED red.
HIGH 15
As soon as the bi-color LED turns green, it’s time to start counting to track how long
until the player releases the button. The timeCounter variable is set to zero, then
another DO…LOOP with an UNTIL condition starts repeating itself. It repeats itself until the
player releases the button (IN3 = 0). Each time through the loop, the BASIC Stamp
delays for 1 ms using PAUSE 1, and it also adds 1 to the value of the timeCounter
variable.
timeCounter = 0 ' Set timeCounter to zero.
PAUSE 1
timeCounter = timeCounter + 1
The last statement in the program is LOOP, which sends the program back to the very first
DO statement.
The “itemized list” of problems and their solutions are discussed below.
Item-1
When a player holds the button for 30 seconds, his score is actually 14000 ms, a
measurement of 14 seconds. This has to be fixed!
It turns out that executing the loop itself along with adding one to the timeCounter
variable takes about 1 ms without the PAUSE 1 command. This is called code overhead,
and it’s the amount of time it takes for the BASIC Stamp to execute the commands. A
quick fix that will improve the accuracy is to simply comment out the PAUSE 1 command
by deleting it or adding an apostrophe to the left of it.
' PAUSE 1
Try commenting PAUSE 1 and test to see how accurate the program is.
Instead of commenting the delay, another way you can fix the program is to multiply
your result by two. For example, just before the DEBUG command that displays the
number of ms, you can insert a command that multiplies the result by two:
timeCounter = timeCounter * 2 ' <- Add this
DEBUG "Your time was ", DEC timeCounter, " ms.", CR, CR
Uncomment the PAUSE command by deleting the apostrophe, and try the
multiply by two solution instead.
Chapter #3: Digital Input - Pushbuttons · Page 95
For precision, you can use the */ operator to multiply by a value with a fraction to make
your answer more precise. The */ operator is not hard to use; here’s how:
1) Place the value or variable you want to multiply by a fractional value before the */
operator.
2) Take the fractional value that you want to use and multiply it by 256.
3) Round off to get rid of anything to the right of the decimal point.
4) Place that value after the */ operator.
Example: Let’s say you want to multiply the timeCounter variable by 3.69.
1) Start by placing timeCounter to the left of the */ operator:
timeCounter = timeCounter */
2) Multiply your fractional value by 256: 3.69 X 256 = 944.64.
3) Round off: 944.64 § 945.
4) Place that value to the right of the */ operator:
timeCounter = timeCounter */ 945
Item-2
Players soon figure out that the delay from red to green is 1 second. After playing it
several times, they get better at predicting when to let go, and their score no longer
reflects their true reaction time.
The BASIC Stamp has a RANDOM command. Here is how to modify your code for a
random number:
At the beginning of your code, add a declaration for a new variable called value,
and set it to 23. The value 23 is called the seed because it starts the pseudo
random number sequence.
timeCounter VAR WORD
value VAR BYTE ' <- Add this
value = 23 ' <- Add this
Just before the pause command, use the RANDOM command to give value a new
“random” value from the pseudo random sequence that started with 23.
RANDOM value ' <- Add this.
DEBUG "Delay time ", ? 1000 + value, CR ' <- Add this.
Page 96 · What’s a Microcontroller?
Modify the PAUSE command so that the random value is added to 1000 (for one
second) in the PAUSE command’s Duration argument.
PAUSE 1000 + value ' <- Modify this.
Item-3
A player that lets go of the button before the light turns green gets an unreasonably
good score (1 ms). Your microcontroller needs to figure out if a player is cheating.
Pseudo code was introduced near the end of Activity #3 in this chapter. Here is some
pseudo code to help you apply an IF…THEN…ELSE statement to solve the problem.
Modify your program by implementing this pseudo code in PBASIC to fix the
cheating player problem.
Chapter #3: Digital Input - Pushbuttons · Page 97
SUMMARY
This chapter introduced the pushbutton and common pushbutton circuits. This chapter
also introduced how to build and test a pushbutton circuit and how to use the BASIC
Stamp to read the state of one or more pushbuttons. The BASIC Stamp was programmed
to make decisions based on the state(s) of the pushbutton(s) and this information was
used to control LED(s). A reaction timer game was built using these concepts. In
addition to controlling LEDs, the BASIC Stamp was programmed to poll a pushbutton
and take time measurements.
Reading individual pushbutton circuits using the special I/O variables built into the
BASIC Stamp (IN3, IN4, etc.) was introduced. Making decisions based on these values
using IF…THEN…ELSE statements, IF…ELSEIF…ELSE statements, and code blocks were
also introduced. For evaluating more than one condition, the AND and OR operators were
introduced. Adding a condition to a DO…LOOP using the UNTIL keyword was introduced
along with nesting DO…LOOP code blocks.
Questions
1. What is the difference between sending and receiving HIGH and LOW signals
using the BASIC Stamp?
2. What does normally open mean?
3. What are the warning signs that indicate you might have made a serious mistake
while wiring your circuit?
4. What happens between the terminals of a normally open pushbutton when you
press it?
5. What two states can a pushbutton circuit be in? What numbers does the BASIC
Stamp use for each of these states?
6. What does a BASIC Stamp I/O pin that is set to input see when a normally open
pushbutton circuit that uses a pull-down resistor is pressed? What does it see
when the pushbutton is not pressed?
7. When does current flow through a pushbutton circuit with a normally open
pushbutton?
8. What is the value of IN3 when a pushbutton connects it to Vdd? What is the
value of IN3 when a pushbutton connects it to Vss?
9. What does the command DEBUG ? IN3 do?
10. What is the difference between a pull-up and pull-down resistor?
Page 98 · What’s a Microcontroller?
11. If you modify a pushbutton circuit that used to have a pull-down resistor so that
it has a pull-up resistor, do you expect to see changes in the values at the I/O
pin?
12. What is the difference between active-low and active-high?
13. What kind of code blocks can be used for making decisions based on the value
of one or more pushbuttons?
14. What does nesting mean?
15. What does the HOME formatter do in the statement DEBUG HOME?
16. What does polling mean?
17. What does code overhead mean?
Exercises
1. Draw a circuit schematic with a normally open pushbutton circuit with a pull-
down resistor connected to P5.
2. Draw a circuit schematic with a normally open pushbutton circuit with a pull-up
resistor connected to P5.
3. Explain how to modify ReadPushbuttonState.bs2 on page 77 so that it reads the
pushbutton every second instead of every ¼ second.
4. Explain how to modify ReadPushbuttonState.bs2 so that it reads a normally open
pushbutton circuit with a pull-up resistor connected to I/O pin P6.
5. Explain how to use a FOR…NEXT loop in PushbuttonControlledLed.bs2 on page
81 so that it flashes the LED fifteen times before checking to see if the button is
pressed again.
6. Explain how to modify PushbuttonControlledLed.bs2 so that the LED stays on
(instead of flashing) when you press and hold the pushbutton.
7. Modify the “Your Turn” version of PushbuttonControlOfTwoLeds.bs2 so that
both LEDs flash when none of the pushbuttons are pressed, and no LEDs flash
when both pushbuttons are pressed and held.
8. Explain how to modify ReactionTimer.bs2 on page 90 so that it uses DO WHILE
instead of LOOP UNTIL. Write down examples of the code blocks you must
change to make it work. Hint: LOOP UNTIL makes its decision using a condition
that causes the program to break out of the loop. DO WHILE makes its decision
based on a condition that keeps the loop repeating.
Projects
1. Test your answer to Exercise 8 by making ReactionTimer.bs2 work with DO
WHILE instead of LOOP UNTIL.
Chapter #3: Digital Input - Pushbuttons · Page 99
2. Refer to the streetlight project in the previous chapter’s Projects section. Some
streetlight controllers do not work on just a timer; they have sensors under the
pavement that detect whether or not a car is waiting at a red light. Modify the
streetlight controller so that the north-south street gets a green light all the time,
but a press on the pushbutton will initialize the east-west sequence to let a car
through.
3. Modify ReactionTimer.bs2 so that it is a two player game. Add a second button
wired to P4 for the second player. HINTS: Use the AND operator in your
DO…LOOP UNTIL loop. Declare two different timeCounter variables,
timeCounterA and timeCounterB. Use IF…THEN reasoning in the DO…LOOP
that increments the counters. You can also borrow some decision making code
from PushbuttonControlOfTwoLeds.bs2 for help making decisions on whether
or not to increment one of the counters.
Further Investigation
The resources listed here are available for free download from the Parallax web site and
are also included on the Parallax CD.
“BASIC Stamp Manual”, Users Manual, Version 2.0c, Parallax Inc., 2000
The BASIC Stamp Manual has more examples you can try and information that
further explains the following: The DEBUG HOME and CLS formatters, input pin
variables such IN3, IN4, and the RANDOM command.
“Basic Analog and Digital”, Student Guide, Version 2.0, Parallax Inc., 2003
Basic Analog and Digital explains binary counting using pushbuttons. It also
uses pushbuttons to introduce a technique for transmitting numbers from one
system to another called synchronous serial communication.
“BASIC Stamp Editor Help File”, PBASIC 2.5 Version 2.0 Parallax Inc., 2003
The PBASIC 2.5 Help File has information on the WHILE and UNTIL conditions
used with DO…LOOP, and information on nesting and IF…THEN…ELSE code blocks,
which is new to PBASIC 2.5 and not included in the BASIC Stamp Manual.
You can find this information by clicking the book icon on your BASIC Stamp
Editor task bar, then selecting PBASIC Reference from the menu in the left
sidebar window. This will open the PBASIC Command Reference alphabetical
listing in the main window. Detailed information can be found by clicking on
each command.
Chapter #4: Controlling Motion · Page 101
Some of these motors require lots of circuitry to help the microcontroller make them
work. Other motors require extra mechanical parts to make them work right in machines.
Of all the different types of motors to start with, the hobby servo that you will experiment
with in this chapter is probably the simplest. As you will soon see, it is easy to control
with the BASIC Stamp, requires little or no additional circuitry, and has a mechanical
output that is easy to connect to things to make them move.
contains the servo’s control circuits, a DC motor, and gears. These parts work together to
take high/low signals from the BASIC Stamp and convert them into positions held by the
servo horn.
Figure 4-1
1 Servo
3
(1) Plug
(2) Cable
(3) Horn
(4) Case
standard servo
www.parallax.com
(1) Servo
(1) Resistor – 470 : (yellow-violet-brown)
(1) LED – any color
sure which Rev it is, Figure 4-2 shows an example of the Rev label on the Board of
Education Rev B.
15 14 13 12
Figure 4-2
Red Board of
Black
Education
X4 X5 Rev B Rev Label
Vdd Vin Vss
X3
Examine the labeling on your carrier board and figure out whether you have a
HomeWork Board or a Board of Education Rev B, or Rev C.
Skip to instructions for connecting the servo to the BASIC Stamp on your carrier
board:
P14
470 :
LED
Vss
Page 104 · What’s a Microcontroller?
Figure 4-5 shows the servo header on the Board of Education Rev C. This is where you
will plug in your servo. This board features a jumper that you can use to connect the
servo’s power supply to either Vin or Vdd. The jumper is the removable black
rectangular piece right between the two servo headers.
Set the jumper to Vdd as shown in Figure 4-5. This involves lifting the
rectangular jumper up off of the pins it is currently on, and replacing it on the
two pins closest to the Vdd label.
The jumper allows you to choose the servo’s power supply (Vin or Vdd). If you are
using a 9 V battery, either setting will work with a single Parallax Standard Servo. Use Vin if
you are using a 6 V battery pack. Use Vdd if you are using a DC supply that plugs into an
AC outlet with output. Before you try to use a DC supply, make sure to check the
specifications for acceptable DC supplies listed in Appendix D: Batteries and Power
Supplies.
15 14 Vdd 13 12
White
Red Red
Black Black
X4 X5
Vdd Vin Vss
X3
+
P15
Figure 4-6
P14 Servo and LED
P13 Indicator on Board
P12
P11 of Education Rev C
P10
P9
P8
P7
P6
P5
standard servo
P4
P3 www.parallax.com
P2
P1
P0
X2
Up until now, you have been using the 3-position switch in the 1 position. Now, you will
move it to the 2 position to turn on the power to the servo header.
Supply power to the servo header by adjusting the 3-position switch as shown in
Figure 4-7. Your servo may move a bit when you connect the power.
Reset
Figure 4-7
Power turned on to
Board of Education
0 1 2 and Servo Header
Figure 4-8
HomeWork Board or Board of
Education – Extra Parts
Figure 4-9 shows the schematic of the servo and LED circuits on the HomeWork Board.
The instructions that come after this figure will show you how to safely build this circuit.
WARNING
Use only a 9 V battery when a servo is connected to the BASIC Stamp HomeWork
Board. Do not use any kind of DC supply or “battery replacer” that plugs into an AC
outlet. Improper use of these devices can cause the activity not to work, or even
permanently damage the servo.
For best results, make sure your battery is new. If you are using a rechargeable battery,
make sure it is freshly recharged. It should also be rated for 100 mAh (milliamp hours) or
more. See Appendix D: Batteries and Power Supplies for more information.
P14
470 :
LED
Vss
Vss
Chapter #4: Controlling Motion · Page 107
WARNING
Use only a 9 V battery when a servo is connected to the Board of Education Rev B.
Do not use any kind of DC supply or “battery replacer” that plugs into an AC outlet.
Improper use of these devices can cause the activity not to work, or even
permanently damage the servo.
For best results, make sure your battery is new. If you are using a rechargeable battery,
make sure it is freshly recharged. It should also be rated for 100 mAh (milliamp hours) or
more. See Appendix D: Batteries and Power Supplies for more information.
Chapter #4: Controlling Motion · Page 109
P14
470 :
LED
Vss
Figure 4-12
Vin Schematic for Servo
and LED Indicator on
Board of Education
P14 White Rev B
Red
Servo
Black
Vss
Disconnect your battery or any other power supply from your board.
Build the LED circuit shown in Figure 4-12.
Connect the servo to the servo header as shown in Figure 4-13.
Page 110 · What’s a Microcontroller?
15 14 13 12
White
Red Red
Black Black
X4 X5
Vdd Vin Vss
X3
+ Figure 4-13
P15 Connecting Servo to
P14
P13 Servo Header on the
P12 Board of Education
P11
P10
Rev B.
P9
P8
P7
P6
P5 standard servo
P4
P3 www.parallax.com
P2
P1
P0
X2
Make sure that the colors on the servo’s cable align properly with the colors
labeled in the picture.
Connect a 9 V battery to Board of Education Rev B. The servo may move a
little bit when you make the connection.
As with HIGH and LOW, the Pin argument is a number that tells the BASIC Stamp which
I/O pin the signal is sent on. The Duration argument is not milliseconds, like it is in the
PAUSE command. For the BASIC Stamp 2, the Duration is the number of 2-millionth-
of-a-second (Ps) time durations that you want the high signal to last.
Chapter #4: Controlling Motion · Page 111
A millionth of a second is called a microsecond. The Greek letter P is used in place of the
word micro and the letter s is used in place of second. This is handy for writing and taking
notes, because instead of writing 2 microseconds, you can write 2 Ps.
Reminder: one thousandth of a second is called a millisecond, and is abbreviated ms.
Fact: 1 ms = 1000 Ps. In other words, you can fit one thousand millionths of a second into
one thousandth of a second.
The next example program will use the PULSOUT command to deliver pulses that instruct
the servo on where to position its horn. FOR…NEXT loops are used to deliver a certain
number of pulses, which cause the servo to hold a position for a certain amount of time.
Figure 4-14
Servo Horn Motion
10 o’clock (left)
standard servo
www.parallax.com
standard servo
www.parallax.com
standard servo
www.parallax.com
2 o’clock (middle)
12 o’clock (right)
What if my servo is different? There are lots of different servos, and many will respond
differently to the signals that TestServo.bs2 sends. Your servo might only rotate to 11
o’clock then 1 o’clock, or maybe to 9 o’clock and then 3 o’clock. It might even rotate the
opposite direction and start in the clockwise direction before it goes counterclockwise. As
long as the motion is easy to observe and consistent, it will work fine for these activities.
You can always modify the example programs to get the servo to behave the way you want.
Re-run the program and verify that the LED flickers dimly. It should be
brightest when the BASIC Stamp sends the 10 o’clock signal and dimmest when
the BASIC Stamp sends the 2 o’clock signal. This is because the LED circuit is
only on for half as long (1 out of 21 ms instead of 2 out of 22 ms).
END
PULSOUT 14, 1000 sends a pulse that lasts 1000 × 2 Ps. That’s 2000 Ps or 2 ms.
Figure 4-15 is called a timing diagram. It shows a picture of the high and low signals and
how long they last. The timing diagram does not show how many pulses are delivered,
but it does give you information about how long the high and low signals last. Each
pulse (high signal) lasts for 2.0 ms. Each pulse is separated by a 20 ms delay while the
signal is low.
Figure 4-15
2.0 ms 2.0 ms Timing Diagram for
Vdd (5 V) 2.0 ms Pulses Every
standard servo
www.parallax.com 20 ms
Servo horn in 10
Vss (0 V) o’clock position.
20 ms
The second FOR…NEXT loop delivers 150 pulses, but this time, each pulse only lasts 1.0
ms. This instructs the servo to turn to the 2 o’clock position for about 3.15 seconds.
FOR COUNTER = 1 TO 150
PULSOUT 14, 500
PAUSE 20
NEXT
PULSOUT 14, 500 sends a pulse that lasts 500 × 2 Ps. That’s 1000 Ps or 1 ms.
Figure 4-15 shows the timing diagram for this pulse train. The pauses between pulses
still last 20 ms.
Page 114 · What’s a Microcontroller?
The last FOR…NEXT loop delivers 150 pulses, each of which lasts 1.5 ms. This instructs
the servo to go to its center position (12 o’clock) for about 3.23 seconds.
FOR counter = 1 TO 150
PULSOUT 14, 750
PAUSE 20
NEXT
PULSOUT 14, 750 sends a pulse that lasts 750 × 2 Ps. That’s 1500 Ps or 1.5 ms.
Figure 4-17 shows the timing diagram for these pulses. While the low time is still 20
ms, the pulse now lasts for 1.5 ms.
Figure 4-17
1.5 ms 1.5 ms
Timing Diagram for
1.5 ms Pulses Every
Vdd (5 V) standard servo
www.parallax.com
20 ms
Servo horn is in 12
Vss (0 V) o’clock position.
20 ms
Do the Math
If you want to convert time from milliseconds to a Duration you can use for PULSOUT,
use this equation.
Duration number of ms u 500
Chapter #4: Controlling Motion · Page 115
For example, if you didn’t already know that the PULSOUT argument for 1.5 ms is 750,
here is how you could calculate it.
Duration 1.5 u 500
750
You can also figure out the Duration of a mystery PULSOUT command using this
equation.
Duration
number of ms ms
500
For example, if you see the command PULSOUT 14, 850, how long does that pulse
really last?
850
number of ms ms
500
1.7 ms
Run the modified program and verify that the servo holds each position for half
as long.
Modify all the FOR...NEXT loops so that they execute twice as many times as
the original program:
FOR counter = 1 to 300
Run the modified program and verify that the servo holds each position for twice
as long.
Modify the PULSOUT command in the first loop so that it reads:
Page 116 · What’s a Microcontroller?
PULSOUT 14,850
Run the modified program, and explain the differences in the positions the servo
turns to and holds.
You can use the Debug Terminal to send messages from your computer to the BASIC
Stamp as shown in Figure 4-18. The BASIC Stamp has to be programmed to listen for
the messages you send using the Debug Terminal, and it also has to store the data you
send in one or more variables.
Figure 4-18
Sending Messages to
the BASIC Stamp
In this activity, you will program the BASIC Stamp to receive two values from the Debug
Terminal:
You will also program the BASIC Stamp to use these values to control the servo.
Later in the program, you can use this value to store a number received by the DEBUGIN
command:
DEBUGIN DEC pulses
When the BASIC Stamp receives a numeric value from the Debug Terminal, it will store
it in the pulses variable. The DEC formatter tells the DEBUGIN command that the
characters you are sending will be digits that form a decimal number. As soon as you hit
the carriage return, the BASIC Stamp will store the digits it received in the pulses
variable as a decimal number, then move on.
Although it is not included in the example program, you can add a line to verify that the
message was processed by the BASIC Stamp.
DEBUG CR, "You sent the value: ", DEC pulses
Figure 4-19
Debug Terminal’s Windowpanes:
ĸ Transmit Windowpane
ĸ Receive Windowpane
Echo is when you send a message, and a copy of that message appears in your Receive
Windowpane. You can click the Echo Off checkbox (shown below) to make a checkmark
appear in it. This will make the Debug Terminal stop displaying these echoes.
Enter ServoControlWithDebug.bs2 into the BASIC Stamp Editor and run it.
If the Transmit Windowpane is too small, resize it using your mouse to click,
hold, and drag the separator downward. The separator is shown just above the
text message: “Enter number of pulses:” in Figure 4-19.
Click the upper, Transmit Windowpane to place your cursor there for typing
messages.
When the Debug Terminal prompts you to, “Enter number of pulses:”, type the
number 100, then press enter.
When the Debug Terminal prompts you to “Enter PULSOUT duration:” type the
number 850, then press enter.
The PULSOUT Duration should be a number between 500 and 1000. If you enter
numbers outside that range, the servo may try to rotate to a position beyond its own
mechanical limits. Although it will not break the servo, it could shorten the device’s lifespan.
The BASIC Stamp will display the message “Servo is running…” while it is sending
pulses to the servo. When it is done sending pulses to the servo, it will display the
message “Done” for one second. Then, it will prompt you to enter the number of pulses
again. Have fun with it, but make sure to follow the directive in the caution box about
staying between 500 and 1000 for your PULSOUT value.
Chapter #4: Controlling Motion · Page 119
Experiment with entering other values between 500 and 1000 for the PULSOUT
Duration and values between 1 and 65534 for the number of pulses.
It takes between 40 and 45 pulses to make the servo hold a position for 1 second.
DO
DEBUG "DONE"
PAUSE 1000
LOOP
The counter variable is declared for use by a FOR…NEXT loop. See Chapter #2, Activity
#3 for details. The pulses and duration variables are used a couple of different ways.
They are both used to receive and store values sent from the Debug Terminal. The
pulses variable is also used to set the number of repetitions in the FOR…NEXT loop that
delivers pulses to the servo, and the duration variable is used to set the duration for the
PULSOUT command.
The rest of the program is nested inside a DO…LOOP without a WHILE or UNTIL argument
so that the commands execute over and over again.
DO
' Rest of program not shown.
LOOP
The DEBUG command is used to send you (the “user” of the software) a message to enter
the number of pulses. Then, the DEBUGIN command waits for you to enter digits that
make up the number and press the Enter key on your keyboard. The digits that you enter
are converted to a value that is stored in the pulses variable. This process is repeated
with a second DEBUG and DEBUGIN command that loads a value into the duration
variable too.
DEBUG CLS, "Enter number of pulses:", CR
DEBUGIN DEC pulses
After you enter the second value, it’s useful to display a message while the servo is
running so that you don’t try to enter a second value:
DEBUG "Servo is running...", CR
While the servo is running, you can gently try to move the servo horn away from the
position it is holding. The servo resists light pressure applied to the horn.
As in previous examples, the counter variable is used as an index for the FOR…NEXT
loop. Up until this example, all the FOR…NEXT loops have used constants such as 10 or
150 for EndValue. In this FOR…NEXT loop, the value of the pulses variable is used to
control the EndValue of the FOR…NEXT loop. This, in turn, controls how many pulses are
delivered to the servo. The end result is that the pulses variable controls how long the
servo holds a given position. Up until now, constant values such as 500, 750, and 1000
were also used for the PULSOUT command’s Duration argument. Look carefully at this
FOR…NEXT loop to see where and how these variables are used:
FOR counter = 1 to pulses
PULSOUT 14, duration
PAUSE 20
NEXT
Take some time to understand this FOR…NEXT loop. It is one of the first examples of the
amazing things you can do with variables in PBASIC command arguments, and it also
highlights how useful a programmable microcontroller like the BASIC Stamp can be.
Let’s imagine that this computer servo control system is one that has been developed for
remote-controlling a door. Perhaps a security guard will use this to open a shipping door
that he or she watches on a remote camera. Maybe a college student will use it to control
doors in a maze that mice navigate in search of food. Maybe a military gunner will use it
to point the cannon at a particular target. If you are designing the product for somebody
else to use, the last thing you want is to give the user (security guard, college student,
military gunner) the ability to enter the wrong number and damage the equipment.
The FOR…NEXT loop causes the servo’s horn to start at around 2 o’clock and then rotate
slowly counterclockwise until it gets to 10 o’clock. Because counter is the index of the
FOR…NEXT loop, it increases by one each time through. The value of counter is also used
in the PULSOUT command’s Duration argument, which means the duration of each
pulse gets a little longer each time through the loop. Since the duration changes, so
does the position of the servo’s horn.
FOR…NEXT loops have an optional STEP argument. The STEP argument can be used to
make the servo rotate faster. For example, you can use the STEP argument to add 8 to
Chapter #4: Controlling Motion · Page 123
counter each time through the loop (instead of 1) by modifying the FOR statement like
this:
FOR counter = 500 TO 1000 STEP 8
You can also make the servo turn the opposite direction by counting down instead of
counting up. In PBASIC, FOR…NEXT loops will also count backwards if the StartValue
argument is larger than the EndValue argument. Here is an example of how to make a
FOR…NEXT loop count from 1000 to 500:
FOR counter = 1000 TO 500
You can combine counting down with a STEP argument to get the servo to rotate more
quickly in the clockwise direction like this:
FOR counter = 1000 TO 500 STEP 20
The trick to getting the servo to turn at different rates is to use these FOR…NEXT loops to
count up and down with different step sizes. The next example program uses these
techniques to make the servo’s horn rotate back and forth at different rates.
DO
LOOP
Why PAUSE 7 instead of PAUSE 20? The command DEBUG DEC5 counter,
CR, CRSRUP takes about 8 ms to execute. This means that PAUSE 12 would maintain
the 20 ms delay between pulses. A few trial and error experiments showed that PAUSE 7
gave the servo the smoothest motion. Your servo may be different.
More DEBUG formatters and control characters are featured in the DEBUG command
that displays the value of the counter variable. This value is printed using the 5-digit
decimal format (DEC5). After the value is printed, there is a carriage return (CR). After the
carriage return, the formatter CRSRUP (cursor up) sends the cursor back up to the previous
line. This causes the new value of counter to be printed over the old value each time
through the loop.
The second FOR…NEXT loop counts downwards from 1000 back to 500 in steps of 20. The
counter variable is also used as an argument for the PULSOUT command in this example,
so the servo horn rotates clockwise.
FOR counter = 1000 TO 500 STEP 20
PULSOUT 14, counter
Chapter #4: Controlling Motion · Page 125
PAUSE 7
DEBUG DEC5 counter, CR, CRSRUP
NEXT
When you are done, you will be able to push one button to get the BASIC Stamp to rotate
the servo in one direction, and another button to get the servo to rotate in the other
direction. When no buttons are pressed, the servo will hold whatever position it moved
to.
Vdd Vdd
P4
220 : Figure 4-20
Pushbutton
P3
Circuits for
220 : Servo Control
10 k: 10 k:
Vss Vss
Add this circuit to the servo+LED circuit that you have been using up to this
point. When you are done your circuit should resemble:
15 14 Vdd 13 12
White
Red Red
Black Black
X4 X5
Vdd Vin Vss
X3 Figure 4-21
+
P15
Board of Education
P14 Rev C Servo
P13 Circuit with
P12
P11 Pushbutton Circuits
P10 Added
P9
P8
P7
P6
P5
standard servo
P4
P3 www.parallax.com
P2
P1
P0
X2
15 14 13 12
White
Red Red
Black Black
X4 X5
Vdd Vin Vss
X3 Figure 4-23
+
P15
Board of Education
P14 Rev B Servo
P13 Circuit with
P12
P11 Pushbutton Circuits
P10 Added
P9
P8
P7
P6
P5
standard servo
P4
P3 www.parallax.com
P2
P1
P0
X2
duration = 750
DO
IF IN3 = 1 THEN
IF duration > 500 THEN
duration = duration - 25
ENDIF
ENDIF
Page 130 · What’s a Microcontroller?
IF IN4 = 1 THEN
IF duration < 1000 THEN
duration = duration + 25
ENDIF
ENDIF
LOOP
SUMMARY
This chapter introduced microcontrolled motion using a servo. A servo is a device that
moves to and holds a particular position based on electronic signals it receives. These
signals take the form of pulses that last anywhere between 1 and 2 ms, and they have to
be delivered every 20 ms for the servo to maintain its position.
A programmer can use the PULSOUT command to make the BASIC Stamp send these
signals. Since pulses have to be delivered every 20 ms for the servo to hold its position,
the PULSOUT and PAUSE commands are usually placed in some kind of loop. Variables
can be used to store the value used in the PULSOUT command’s Duration argument.
This causes the servo’s horn to rotate in steps.
In this chapter, a variety of ways to get the values into the variables were presented. The
variable can receive the value from your Debug Terminal using the DEBUGIN command.
The value of the variable can pass through a sequence of values if the same variable is
used as the index for a FOR…NEXT loop. This technique can be used to cause the servo to
make sweeping motions. IF…THEN statements can be used to monitor pushbuttons and
add or subtract from the variable used in the PULSOUT command’s Duration argument
based on whether or not a certain button is pressed. This allows both position control and
sweeping motions depending on how the program is constructed and how the pushbuttons
are operated.
Questions
1. What appliances or tools have you relied on in the last week that might contain a
microcontroller that controls motion?
2. What are the four external parts on a servo? What are they used for?
3. Is an LED circuit required to make a servo work?
4. What command controls the low time in the signal sent to a servo? What
command controls the high time?
5. What programming element can you use to control the amount of time that a
servo holds a particular position?
6. What command really controls the position of the servo? What is the name of
the argument in the command that, if changed, will cause the servo’s position to
change?
7. When a servo is under BASIC Stamp control, what does the LED’s brightness
tell you about the signal it is sending to the servo?
Page 132 · What’s a Microcontroller?
8. How do you use the Debug Terminal to send messages to the BASIC Stamp?
What programming command is used to make the BASIC Stamp receive
messages from the Debug Terminal?
9. If the user is sending messages that tell the servo what position to turn to, what
kind of code block is helpful to make sure that he/she does not enter a number
that is too large or too small?
10. What’s the name of the argument used to make a FOR…NEXT loop add or subtract
a value greater than 1 each time through the loop? How do you make a
FOR…NEXT loop count backwards?
11. What does the servo do if you use the index of a FOR…NEXT loop as the argument
for the PULSOUT command’s Duration argument?
12. What type of code block can you write to limit the servo’s range of motion?
Exercises
1. The command PULSOUT 14, 750 delivers a 1.5 ms pulse on I/O pin P14.
Calculate how long the pulse would last if the Duration argument of 750 is
changed to 600. Repeat this calculation for these values: (a) 650, (b) 50000, (c)
1, (d) 2, (e) 2000.
2. Write the command required to deliver a 5.25 ms pulse on I/O pin P15.
3. Write a loop that delivers a 10.125 ms pulse on I/O pin P15 every 50 ms: (a)
indefinitely, (b) for 10 repetitions, (c) indefinitely, so long as the pushbutton
connected to P3 sends a low signal, (d) for ten seconds after a press to the
pushbutton connected to P4 is detected.
4. Write a code block that sweeps the value of the PULSOUT command controlling a
servo from a duration of 700 to 800, then back to 700 again, in increments of (a)
1, (b) 2, (c) 3, (d) 4.
5. Add a nested FOR…NEXT loop to your answer to exercise 4 (d) so that it delivers
ten pulses before incrementing the PULSOUT command’s Duration argument by
4.
Projects
1. Modify ServoControlWithDebug.bs2 so that it monitors a kill switch. When the
kill switch (the pushbutton connected to P3) is being pressed by the user, the
Debug Terminal should not accept any commands. It should display the
message: “Press Start switch to start machinery”. When the start switch (the
pushbutton connected to P4) is pressed, the program will function normally, like
it does when you run the example program. If power is disconnected and
Chapter #4: Controlling Motion · Page 133
reconnected, the program should behave as though the kill switch has been
pressed. OPTIONAL: Add a bi-color LED circuit connected to P12 and P13.
The bi-color LED should be red after the kill switch has been pressed and green
after the start switch has been pressed.
Further Investigation
The servo, and using sensors to control servos, can be investigated in detail in a variety of
Stamps in Class texts.
“Advanced Robotics: with the Toddler”, Student Guide, Version 1.2, Parallax Inc.,
2003
Advanced Robotics: with the Toddler uses servos to control the motions of the
Parallax Toddler robot’s legs. Although we take walking for granted,
programming a machine to walk, maneuver, and keep its balance can be very
challenging. This walking robot is recommended for advanced students who
have already mastered the concepts in What’s a Microcontroller? and either
Robotics! or SumoBot.
with your own autonomous Mini-Sumo class robot. This textbook offers a
condensed presentation of the Robotics! text material applied towards the goal of
winning a robotic sumo wrestling contest.
Chapter #5: Measuring Rotation · Page 135
Dials can also be found in audio equipment, where they are used to adjust how music and
voices sound. Figure 5-1 shows a simple example of a dial with a knob that is turned to
adjust the speaker’s volume. By turning the knob, a circuit inside the speaker changes,
and the volume of the music the speaker plays changes. Similar circuits can also be
found inside joysticks, and even inside the servo used in Chapter #4: Controlling Motion.
Figure 5-1
Volume
Adjustment
on a Speaker
Figure 5-2
A Few
Potentiometer
Examples
Figure 5-3 shows the schematic symbol and part drawing of the potentiometer you will
use in this chapter. Terminals A and B are connected to a 10 k: resistive element.
Terminal W is called the wiper terminal, and it is connected to a wire that touches the
resistive element somewhere between its ends.
A Figure 5-3
Potentiometer
10 k: Schematic Symbol
Pot W and Part Drawing
B
Figure 5-4 shows how the wiper on a potentiometer works. As you adjust the knob on
top of the potentiometer, the wiper terminal contacts the resistive element at different
places. As you turn the knob clockwise, the wiper gets closer to the A terminal, and as
you turn the knob counterclockwise, the wiper gets closer to the B terminal.
A
+
Figure 5-4
+ 10 k: Adjusting the
Pot W
A Potentiometer’s Wiper
W Terminal
B
B
Chapter #5: Measuring Rotation · Page 137
Tip: Use a needle-nose pliers to straighten the kinks out of the potentiometer’s legs before
plugging the device into the breadboard. When the potentiometer’s legs are straight, they
maintain better contact with the breadboard sockets.
Page 138 · What’s a Microcontroller?
Vdd
Vdd Vin Vss
X3
P15 +
220 : P14
P13
P12 Figure 5-5
P11
P10
Potentiometer-LED
Pot P9 Test Circuit
10 k: P8
P7
P6
LED P5
nc
X
P4
P3
P2
Vss P1
P0
X2
Handle with care: If your potentiometer will not turn this far, do not try to force it. Just turn
it until it reaches its mechanical limit; otherwise, it might break.
Figure 5-6
Potentiometer Input Shaft
(a) (c) (e)
(a) through (f) show the
(b) (d) (f) potentiometer’s wiper
terminal set to different
positions.
turn the potentiometer’s input shaft, the resistance between the A and W terminals
changes. This in turn changes the current flow through the LED circuit.
This capacitor has a positive (+) and a negative (-) terminal. The negative terminal is
the lead that comes out of the metal canister closest to the stripe with a negative (–) sign.
Always make sure to connect these terminals as shown in the circuit diagrams. Connecting
one of these capacitors incorrectly can damage it. In some circuits, connecting this type of
capacitor incorrectly and then connecting power can cause it to rupture or even explode.
Figure 5-7
3300 µ
3300 PF Capacitor
Schematic Symbol
3300 µF and Part Drawing
F
SAFETY
Always observe polarity when connecting the 3300 PF capacitor. Remember, the
negative terminal is the lead that comes out of the metal canister closest to the stripe with a
negative (–) sign. Use Figure 5-7 to identify the (+) and (-) terminals.
Your 3300 PF capacitor will work fine in this experiment so long as you make sure that the
positive (+) and negative (-) terminals are connected EXACTLY as shown in Figure 5-8 and
Figure 5-9.
Never reverse the supply polarity on the 3300 PF or any other polar capacitor. The
voltage at the capacitor’s (+) terminal must always be higher than the voltage at its (-)
terminal. Vss is the lowest voltage (0 V) on the Board of Education and BASIC Stamp
HomeWork Board. By connecting the capacitor’s negative terminal to Vss, you ensure that
the polarity across the capacitor’s terminals will always be correct.
Wear safety goggles or safety glasses during this activity.
Always disconnect power before you build or modify circuits.
Keep your hands and face away from this capacitor when power is connected.
With power disconnected, build the circuit as shown starting with a 470 :
resistor in place of the resistor labeled Ri.
Chapter #5: Measuring Rotation · Page 141
Figure 5-8
P7 Schematic for Viewing
220 : RC-time Voltage Decay
R1 = 470 :
3300 µF Ri R2 = 1 k:
Four different resistors
R3 = 2 k: will be used as Ri
R4 = 10 k: shown in the schematic.
First, the schematic will
be built and tested with
Ri = 470 :, then Ri = 1
Vss
k:, etc.
R4 R3 R2 R1
Figure 5-9
F
Vdd Vin Vss
- 00
µ Wiring Diagram for
X3
33 Figure 5-8
+
P15
P14
Make sure that the
+
P13
P12 negative lead of the
P11 capacitor is connected
P10
P9 on your board the same
P8 way it is shown in this
P7
P6 figure, with the negative
P5 lead connected to Vss.
P4
P3
P2
P1
P0
X2
Record the measured time (the capacitor’s discharge time) in the 470 : row of
Table 5-1.
Disconnect power from your Board of Education or BASIC Stamp HomeWork
Board.
Remove the 470 : resistor labeled Ri in Figure 5-8 and Figure 5-9 on page 141,
and replace it with the 1 k: resistor.
Reconnect power to your board.
Record your next time measurement (for the 1 k: resistor).
Repeat these steps for each resistor value in Table 5-1.
DEBUG CLS
HIGH 7
DEBUG "Capacitor Charging...", CR
FOR counter = 5 TO 0
PAUSE 1000
DEBUG DEC2 counter, CR, CRSRUP
NEXT
DO
PAUSE 100
timeCounter = timeCounter + 1
Chapter #5: Measuring Rotation · Page 143
DEBUG ? IN7
DEBUG DEC5 timeCounter, CR, CRSRUP, CRSRUP
END
The command DEBUG CLS clears the Debug Terminal so that it doesn’t get cluttered with
successive measurements. HIGH 7 sets P7 high and starts charging the capacitor, then a
“Capacitor charging…” message is displayed. After that, a FOR…NEXT loop counts
down while the capacitor is charging. As the capacitor charges, the voltage across its
terminals increases toward anywhere between 2.5 and 4.9 V (depending on the value of
Ri).
DEBUG CLS
HIGH 7
DEBUG "Capacitor Charging...", CR
FOR counter = 5 TO 0
PAUSE 1000
DEBUG DEC2 counter, CR, CRSRUP
NEXT
In order to let the capacitor discharge itself through the Ri resistor, the I/O pin is changed
from HIGH to INPUT. As an input, the I/O pin, has no effect on the circuit, but it can
sense high or low signals. As soon as the I/O pin releases the circuit, the capacitor
Page 144 · What’s a Microcontroller?
discharges as it feeds current through the resistor. As the capacitor discharges, the
voltage across its terminals gets lower and lower (decays).
INPUT 7
Back in the pushbutton chapter, you used the BASIC Stamp to detect a high or low signal
using the variables IN3 and IN4. At that time, a high signal was considered Vdd, and a
low signal was considered Vss. It turns out that a high signal is any voltage above 1.4 V.
Of course, it could be up to 5 V. Likewise, a low signal is anything between 1.4 V and 0
V. This DO…LOOP checks P7 every 100 ms until the value of IN7 changes from 1 to 0,
which indicates that the capacitor voltage decayed below 1.4 V.
DO
PAUSE 100
timeCounter = timeCounter + 1
DEBUG ? IN7
DEBUG DEC5 timeCounter, CR, CRSRUP, CRSRUP
END
These capacitors do not have + and – terminals. You can safely connect these
capacitors to a circuit without worrying about positive and negative terminals.
Page 146 · What’s a Microcontroller?
104
Figure 5-10
0.1 µF Ceramic Capacitors
P7
nc
220 :
X
Pot
0.1 µF Figure 5-11
10 k:
BASIC Stamp
RCTIME Circuit
with Potentiometer
Vss
Chapter #5: Measuring Rotation · Page 147
Vin Vss
X3
P15
P14
P13
P12
P11
P10 Figure 5-12
P9
P8 Wiring Diagram for
P7 Figure 5-11
P6
P5
P4
P3
P2
P1
P0
X2
DO
HIGH 7
PAUSE 100
RCTIME 7, 1, time
DEBUG HOME, "time = ", DEC5 time
LOOP
Page 148 · What’s a Microcontroller?
Before the RCTIME command is executed, the capacitor is fully charged. As soon as the
RCTIME command executes, the BASIC Stamp changes the I/O pin from an output to an
input. As an input, the I/O pin looks about the same to the circuit as when the pushbutton
was released (open circuit) in Activity #2. The RCTIME command is a high speed version
of the polling that was used in Activity #2, and it measures the amount of time it takes for
the capacitor to lose its charge and fall below the I/O pin’s 1.4 V input threshold. Instead
of counting in 100 ms increments, the RCTIME command counts in 2 Ps increments.
An example of a model airplane and its radio controller are shown in Figure 5-13. The
model airplane has servos to control all its flaps and the gas engine’s throttle settings.
These servos are controlled using the radio control (RC) unit in front of the plane. This
RC unit has potentiometers under a pair of joysticks that are used to control the servos
that in turn control the plane’s elevator and rudder flaps.
Figure 5-13
Model Airplane and
Radio Controller
How the RC Unit Controls the Airplane: The potentiometers under the joysticks are
monitored by a circuit that converts the position of the joystick into control pulses for the
servo. These control pulses are then converted to radio signals and transmitted by the
handheld controller to a radio receiver in the model airplane. The radio receiver converts
these signals back to control pulses which then position the servos.
If you have not already completed the Your Turn section of the previous activity,
go back and complete it now.
For this next example, here are the time values that were measured by a Parallax
technician; your values will probably be slightly different:
So how can these input values be adjusted so that they map to the values of 500 and 1000
that are needed to control the servo with the PULSOUT command? The answer is by using
multiplication and addition. First, multiply the input values by something to make the
difference between the clockwise (minimum) and counterclockwise (maximum) values
500 instead of almost 700. Then, add a constant value to the result so that its range is
Chapter #5: Measuring Rotation · Page 151
from 500 to 1000 instead of 1 to 500. In electronics, these operations are called scaling
and offset.
500
time(maximum) 691u 691u 0.724 500
691
500
time(minimum) 1u 0.724
691
After the values are scaled, here is the addition (offset) step.
The */ operator that was introduced on page 95 is built into PBASIC for scaling by
fractional values, like 0.724. Here again are the steps for using */ applied to 0.724:
1. Place the value or variable you want to multiply by a fractional value before the
*/ operator.
time = time */
2. Take the fractional value that you want to use and multiply it by 256.
3. Round off to get rid of anything to the right of the decimal point.
That takes care of the scaling, now all we need to do is add the offset of 500. This can be
done with a second command that adds 500 to time:
time = time */ 185
time = time + 500
Page 152 · What’s a Microcontroller?
Now, time is ready to be recycled into the PULSOUT command’s Duration argument.
time = time */ 185 ' Scale by 0.724.
time = time + 500 ' Offset by 500.
PULSOUT 14, time ' Send pulse to servo.
DO
HIGH 7
PAUSE 10
RCTIME 7, 1, time
time = time */ 185 ' Scale by 0.724 (X 256 for */).
time = time + 500 ' Offset by 500.
PULSOUT 14, time ' Send pulse to servo.
LOOP
Run the modified program and check your work. Because the values were
rounded off, the limits may not be exactly 500 and 1000, but they should be
pretty close.
These alias names are just about always declared near the beginning of the program so
that they are easy to find.
Now, anywhere in your program that you want to use one of these values, you can use the
words offset or scaleFactor instead. For example,
time = time */ scaleFactor ' Scale by 0.724.
time = time + offset ' Offset by 500.
You can also apply the same technique with the I/O pins. For example, you can declare a
constant for I/O pin P7.
rcPin CON 7
There are two places in the previous example program where the number 7 is used to
refer to I/O pin P7. The first can now be written as:
HIGH rcPin
If you change your circuit later, all you have to do is change the value in your constant
declaration, and both the HIGH and RCTIME commands will be automatically updated.
Likewise, if you have to recalibrate your scale factor or offset, you can also just change
the CON directives at the beginning of the program.
Assigning an alias is what you do when you give a variable, constant or I/O pin a name
using VAR, CON, or PIN.
Page 154 · What’s a Microcontroller?
DO
HIGH rcPin
PAUSE delay
RCTIME rcPin, 1, time
time = time */ scaleFactor ' Scale scaleFactor.
time = time + offset ' Offset by offset.
PULSOUT servoPin, time ' Send pulse to servo.
DEBUG HOME, DEC5 time ' Display adjusted time value.
LOOP
rcPin CON 8
Add this command before the DO…LOOP so that you can see that the rcPin
constant really is just a way of saying the number eight:
DEBUG ? rcPin
Re-run the program and verify that the HIGH and RCTIME commands are still
functioning properly on the different I/O pin with just one change to the rcPin
CON directive.
Page 156 · What’s a Microcontroller?
SUMMARY
This chapter introduced the potentiometer, a part often found under various knobs and
dials. The potentiometer has a resistive element that typically connects its outer two
terminals and a wiper terminal that contacts a variable point on the resistive element. The
potentiometer can be used as a variable resistor if the wiper terminal and one of the two
outer terminals is used in a circuit.
The capacitor was also introduced in this chapter. A capacitor can be used to store and
release charge. The amount of charge a capacitor can store is related to its value, which
is measured in Farads, (F). The P is engineering notation for micro, and it means one-
millionth. The capacitors used in this chapter’s activities ranged from 0.01 to 3300 PF.
A resistor and a capacitor can be connected together in a circuit that takes a certain
amount of time to charge and discharge. This circuit is commonly referred to as an RC-
time circuit. The R and C in RC-time stand for resistor and capacitor. When one value
(C in this chapter’s activities) is held constant, the change in the time it takes for the
circuit to discharge is related to the value of R. When the value of R changes, the value
of the time it takes for the circuit to charge and discharge also changes. The overall time
it takes the RC-time circuit to discharge can be scaled by using a capacitor of a different
size.
Polling was used to monitor the discharge time of a capacitor in an RC circuit where the
value of C was very large. Several different resistors were used to show how the
discharge time changes as the value of the resistor in the circuit changes. The RCTIME
command was then used to monitor a potentiometer (a variable resistor) in an RC-time
circuit with smaller value capacitors. Although these capacitors cause the discharge
times to range from roughly 2 to 1500 Ps (millionths of a second), the BASIC Stamp has
no problem tracking these time measurements with the RCTIME command. The I/O pin
must be set HIGH, and then the capacitor in the RC-time circuit must be allowed to charge
by using PAUSE before the RCTIME command can be used.
may find yourself using multiplication and division as well. The CON directive can be
used at the beginning of a program to substitute a name for a number. As with naming
variables, naming constants is also called creating an alias. After an alias is created, the
name can be used in place of the number throughout the program. This can come in
handy, especially if you need to use the same number in 2, 3, or even 100 different places
in the program. You can change the number in the CON directive, and all 2, 3, or even
100 different instances of that number are automatically updated next time you run the
program.
Questions
1. What are five examples of devices that use dials and knobs?
2. When you turn the dial or knob on a sound system, what component are you
most likely adjusting?
3. In a typical potentiometer, is the resistance between the two outer terminals
adjustable?
4. When the input shaft on a potentiometer is turned, what happens to the resistance
at each of its three terminals? What relationships exist between the different
possible pairs of the three terminals? What effect does this have on an LED
circuit connected to the potentiometer’s A and W terminals?
5. How is a capacitor like a rechargeable battery? How is it different?
6. What can you do with an RC-time circuit to give you an indication of the value
of a variable resistor?
7. Let’s say you have a voltage source that varies connected to P8. What happens
to IN8 as the voltage at that I/O pin goes from above 1.4 V to below 1.4 V?
What do you think will happen if the voltage increases from below to above 1.4
V?
8. What happens to the RC discharge time as the value of R (the resistor) gets
larger or smaller?
9. If you want to scale the timer measurements on an RC time circuit so that it takes
100 times as long, what part would you replace? How is the new part different
from the old part?
10. What are the names of the three arguments the RCTIME command uses? What is
the function of each argument? HINT: you will have to look up the answer to
this question in the BASIC Stamp Manual.
11. If the values that come from the RCTIME measurement are not the correct values
for the PULSOUT command, you can do one of two things. The first option (not
recommended) is to change and tune the circuit until it gives you just the right
Page 158 · What’s a Microcontroller?
Exercises
1. Let’s say that you have a 0.5 PF capacitor in an RC timer circuit, and you want
the measurement to take 10-times as long. Calculate the value of the new
capacitor.
2. Given a variable called measurement, and an RC-time circuit connected to I/O
pin P6, write a command that measures the circuit’s discharge time and stores it
in the variable.
3. Rewrite your answer for the previous exercise so that no numbers are used in the
commands, only aliases for constant value and variables.
Projects
1. Add a bi-color LED circuit to Activity #4. Modify the example program so that
the bi-color LED is red when the servo is rotating counterclockwise, green when
the servo is rotating clockwise, and off when the servo holding its position.
2. Add on/off pushbuttons to the example in Activity #4. Modify the example
program so that it runs after you press and release the ‘on’ button and does not
run after you press and release the ‘off’ button. If you press and release the ‘on’
button after pressing and releasing the ‘off’ button, the program should resume
potentiometer control of the servo.
3. Build a circuit that controls the speed an LED flashes based on the position of a
potentiometer RC-time circuit. When the potentiometer is all the way clockwise,
the LED should flash on and off rapidly, around 10 times per second. When the
potentiometer is all the way counterclockwise, the LED should flash on and off
slowly, once every 5 to 10 seconds.
4. Use IF…THEN to modify the example program from Activity #4 so that the servo
only rotates between PULSOUT values of 650 and 850.
5. Program the BASIC Stamp to scale the value measured by the RCTIME command
so that the full range of the time measurements that result from the
potentiometer’s motion maps to a range of servo PULSOUT values between 650
and 850. HINTS: You will need to multiply using the * operator and divide
using the / operator to scale your time measurement to a range of 200. For
example, if it turns out that you need to scale it to 2/5 of the value, multiply time
Chapter #5: Measuring Rotation · Page 159
by 2 first, and then divide that result by 5. After that, you will still need to go
through the process of adding an offset as shown in Activity #4.
Further Investigation
Several different electronic components, concepts and techniques were incorporated in
this chapter. Some of the more notable examples are:
“Advanced Robotics: with the Toddler”, Student Workbook, Version 1.2, Parallax
Inc., 2003
“Robotics!”, Student Workbook, Version 1.5, Parallax Inc., 2000
“SumoBot”, Student Workbook, Version 1.1, Parallax Inc., 2002
Every Stamps in Class robotics text uses RCTIME to measure resistive sensors to
detect a variety of conditions. Each condition leads to math and decisions, and
the end result is robot movement.
“Basic Analog and Digital”, Student Guide, Version 2.0, Parallax Inc., 2003
Basic Analog and Digital uses the potentiometer to create a variable voltage,
called a voltage divider, which is analyzed by an analog to digital converter. A
potentiometer is also used as an input device to set the frequency of a 555 timer.
This text takes a closer look at the math involved in RC voltage decay.
Figure 6-1
Digital Clock 7-Segment
Display on Oven Door
Each of the three digits in Figure 6-1 is called a 7-segment display. In this chapter, you
will program the BASIC Stamp to display numbers and letters on a 7-segment display.
Common
Cathode
10 9 8 7 6
G F A B
A
Figure 6-2
F B
7-Segment
G LED Display
E C Part Drawing
D
and Pin Map
E D C DP
1 2 3 4 5
Common
Cathode
Pin Map: Figure 6-2 is an example of a pin map. A pin map contains useful information that
helps you connect a part to other circuits. Pin maps usually show a number for each pin, a
name for each pin, and a reference. Take a look at Figure 6-2. Each pin is numbered, and
the name for each pin is the segment letter next to the pin. The reference for this part is its
overall appearance. You know by looking at the top of the display that pin 1 is closest to the
lower-left corner of the display. Other parts have more subtle references, such as the flat
spot on a regular LED’s case.
Figure 6-3 shows a schematic of the LEDs inside the 7-segment LED display. Each LED
anode is connected to an individual pin. All the cathodes are connected together by wire
inside the part. Because all the cathodes share a common connection, the 7-segment LED
display can be called a “common cathode” display. By connecting either pin 3 or pin 8 of
the part to Vss, you will connect all the LED cathodes to Vss.
Chapter #6: Digital Display · Page 163
1 4 6 7 9 10 5
E C B A F G DP
Figure 6-3
LED’s 7-Segment
Schematic
3 8
What’s the x with the nc above it in the schematic? The nc stands for not connected or
no-connect. It indicates that a particular pin on the 7-segment LED display is not connected
to anything. The x at the end of the pin also means not connected. Schematics sometimes
use just the x or just the nc.
Page 164 · What’s a Microcontroller?
Vdd
1 k:
nc
X nc nc nc nc nc nc
X
Figure 6-4
1 4 6 7 9 10 5 Test Circuit
Schematic for
E C B A F G DP
the ‘A’
Segment LED
Display.
LED’s
3 8
X
nc
Vss
P0
P1
P2
P3
P4
P5
P6
P7
P8
P9
P10
P11
P12
P13
P14
P15
X2
X3
Vdd
Figure 6-5
Test Circuit
Wiring Diagram
Vin
Display
Disconnect power, and modify the circuit by connecting the resistor to the B
LED input as shown in Figure 6-6 and Figure 6-7.
Chapter #6: Digital Display · Page 165
Vdd
1 k:
nc nc nc nc nc nc nc
X
1 4 6 7 9 10 5 Figure 6-6
Test Circuit
E C B A F G DP Schematic for
the ‘B’ Segment
LED Display.
LED’s
3 8
X
nc
Vss
P0
P1
P2
P3
P4
P5
P6
P7
P8
P9
P10
P11
P12
P13
P14
P15
X2
X3
Vdd
Figure 6-7
Test Circuit
Wiring Diagram
Vin
Display
1 k:all)
Figure 6-8
nc nc nc
Hardwired Digit ‘3’
X
X
1 4 6 7 9 10 5
The digit “3” is
E C B A F G DP shown on the 7-
segment LED
display using the
LED’s
circuit shown in this
schematic.
3 8
X
nc
Vss
P0
P1
P2
P3
P4
P5
P6
P7
P8
P9
P10
P11
P12
P13
P14
P15
X2
X3
Vdd
Figure 6-9
Vin
Build and test the circuit shown in Figure 6-8 and Figure 6-9, and verify that it
displays the number three.
Draw a schematic for the number two.
Build and test the circuit to make sure it works. Trouble-shoot if necessary.
Repeat for the letter ‘A’.
Chapter #6: Digital Display · Page 167
Schematic and pin map: If you are trying to build the circuit from the schematic in Figure 6-
10 without relying on Figure 6-11, make sure to consult the 7-segment LED display’s pin
map (Figure 6-2, page 162).
Page 168 · What’s a Microcontroller?
1 k:
(All)
P15
P14
P13
P12
P11 Figure 6-10
P10 BASIC Stamp
Controlled 7-
P9
Segment LED
P8 Display
E C DP G F A B Schematic
LED’s
common
Vss
Be careful with the resistors connected to P13 and P14. Look carefully at the resistors
connected to P13 and P14 in Figure 6-11. There is gap between these two resistors. The
gap is shown because pin 8 on the 7-segment LED display is left unconnected. A resistor
connects I/O pin P13 to 7-segment LED display pin 9. Another resistor connects P14 to 7-
segment LED display pin 7.
Chapter #6: Digital Display · Page 169
DP
EDC GFAB
P0
P1
P2
P3
P4
P5
P6
P7
P8
P9
P10
P11
P12
P13
P14
P15
X2
Figure 6-11
X3
Wiring Diagram for
Figure 6-10
Vdd
Use the segment
Vin
letters above this
diagram as a
reference.
Vss
Parallel Device: The 7-segment LED display is called a parallel device because you have
to use more than one I/O line at a time to send data (high and low information) to the device.
In the case of this 7-segment LED display, it takes 8 I/O pins to instruct the device what to
do.
Parallel Bus: The wires that transmit the HIGH/LOW signals from the BASIC Stamp to the
7-segment LED display are called a parallel bus. Note that these wires are drawn as
parallel lines in Figure 6-10. The term parallel kind of makes sense given the geometry of
the schematic.
'{$STAMP BS2}
'{$PBASIC 2.5}
FOR pinCounter = 8 TO 15
NEXT
In this activity, you will use 8-digit binary numbers instead of HIGH and LOW commands
to control the high/low signals sent by BASIC Stamp I/O pins. By setting special
variables called DIRH and OUTH equal to the binary numbers, you will be able to control
the high/low signals sent by all the I/O pins connected to the 7-segment LED display
circuit with a single PBASIC command.
Chapter #6: Digital Display · Page 171
8 bits: A binary number that has 8 digits is said to have 8 bits. Each bit is a slot where you
can store either a 1 or a 0.
A byte is a variable that contains 8 bits. There are 256 different combinations of zeros and
ones that you can use to count from 0 to 255 using 8 bits. This is why a byte variable can
store a number between 0 and 255.
'{$STAMP BS2}
'{$PBASIC 2.5}
PAUSE 1000
OUTH = %11010110 ' 3
PAUSE 1000
OUTH = %10110100 ' 4
PAUSE 1000
OUTH = %01110110 ' 5
PAUSE 1000
OUTH = %01110111 ' 6
PAUSE 1000
OUTH = %11000100 ' 7
PAUSE 1000
OUTH = %11110111 ' 8
PAUSE 1000
OUTH = %11110110 ' 9
PAUSE 1000
Figure 6-12
Using DIRH
and OUTH to
Vdd
X2
P15
P14
P13
P12
P10
P11
P9
P8
P7
P6
P5
P4
P3
P2
P1
P0
OUTH = %00000000
DIRH = %11111111
Chapter #6: Digital Display · Page 173
gets all the I/O pins (P8 through P15) ready to send the low signals. If they all send low
signals, it will turn all the LEDs in the 7-segment LED display off. If you wanted all the
I/O pins to send the high signal, you could use OUTH = %11111111 instead.
What does % do? The % is used to tell the BASIC Stamp Editor that the number is a binary
number. For example, the binary number %00001100 is the same as the decimal number
12. As you will see in this activity, binary numbers can make many programming tasks
much easier.
The low signals will not actually be sent by the I/O pins until you use the DIRH variable
to change all the I/O pins from input to output. The command:
DIRH = %11111111
sets all I/O pins P8 through P15 to output. As soon as this command is executed, P8
through P15 all start sending the low signal. This is because the command OUTH =
%00000000 was executed just before this DIRH command. As soon as the DIRH command
set all the I/O pins to output, they started sending their low signals. You can also use
DIRH = %00000000 to change all the I/O pins back to inputs.
Before I/O pins become outputs: Up until the I/O pins are changed from input to output,
they just listen for signals and update the INH variable. This is the variable that contains
IN8, IN9, up through IN15. These variables can be used the same way that IN3 and
IN4 were used for reading pushbuttons in Chapter #3.
All BASIC Stamp I/O pins start out as inputs. This is called a “default”. You have to tell a
BASIC Stamp I/O pin to become an output before it starts sending a high or low signal. Both
the HIGH and LOW commands automatically change a BASIC Stamp I/O pin’s direction to
output. Placing a 1 in the DIRH variable also makes one of the I/O pins an output.
Figure 6-13 shows how to use the OUTH variable to selectively send high and low signals
to P8 through P15. A binary-1 is used to send a high signal, and a binary-0 is used to
send a low signal. This example displays the number three on the 7-segment LED
display:
' BAFG.CDE
OUTH = %11010110
Page 174 · What’s a Microcontroller?
Vss
Vin
Figure 6-13
Using OUTH to
Control the
Vdd
High/Low Signals
of P8 – P15.
X3
X2
P15
P14
P13
P12
P10
P11
P9
P8
P7
P6
P5
P4
P3
P2
P1
P0
‘ BAFG.CDE
OUTH = %11010110
The display is turned so that the three on the display is upside-down because it more
clearly shows how the values in OUTH line up with the I/O pins. The command OUTH =
%11010110 uses binary zeros to set I/O pins P8, P11, and P13 low, and it uses binary
ones to set P9, P10, P12, P14 and P15 high. The line just before the command is a
comment that shows the segment labels line up with the binary value that turns that
segment on/off. The next example program shows how to set OUTH to binary numbers to
make the 7-segment LED display count from zero to nine.
Inside the HIGH and LOW commands: The command HIGH 15 is really the same as
OUT15 = 1 followed by DIR15 = 1. Likewise, the command LOW 15 is the same as
OUT15 = 1 followed by DIR15 = 1. If you want to change P15 back to an input, use
DIR15 = 0. You can then use IN15 to detect (instead of send) high/low signals.
Decimal vs. Hexadecimal The basic digits in the decimal (base-10) number system are: 0,
1, 2, 3, 4, 5, 6, 7, 8, and 9. In the hexadecimal (base-16) number system the basic digits
are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, b, C, d, E, F. Base-16 is used extensively in both computer
and microcontroller programming. Once you figure out how to display the characters A
through F, you can further modify your program to count in hexadecimal from 0 to F.
There are two variables used in this command, index and value. If the index is 0,
value stores the 7. If index is 1, the value stores 85. Since index is 2, in this
example, the LOOKUP command places 19 into value, and that’s what the Debug
Terminal displays.
index = 2
DEBUG ? index
DEBUG ? value, CR
END
'{$STAMP BS2}
'{$PBASIC 2.5}
OUTH = %00000000
DIRH = %11111111
FOR index = 0 TO 9
PAUSE 1000
NEXT
DIRH = %00000000
END
Add the potentiometer circuit to the 7-segment LED display circuit as shown in
Figure 6-15.
Page 178 · What’s a Microcontroller?
P5
220 :
Pot Figure 6-14
10 k: 0.1 µF
Schematic of
Potentiometer
X
nc Circuit Added to
the Project
Vss
P0
P1
P2
P3
P4
P5
P6
P7
P8
P9
P10
P11
P12
P13
P14
P15
X2
X3
Vdd
Figure 6-15
Vin
Project Wiring
Diagram
Vss
Programming the Dial and Display
There is a useful command called the LOOKDOWN, and yes, it is the reverse of the LOOKUP
command. While the LOOKUP command gives you a number based on an index, the
LOOKDOWN command gives you an index based on a number.
Re-run the program after each change to the value variable and note which
value from the list gets placed in the index variable.
Unless you tell it to make a different kind of comparison, the LOOKDOWN command checks
to see if a value is equal to an entry in the list. You can also check to see if a value is
greater than, less than or equal to, etc. For example, to search for an entry that is less
than or equal to the value variable, use the <= operator just before the first bracket that
starts the list.
Experiment with different values and see if the index variable displays what you
would expect.
Trick question: What happens if your value is greater than 167? This little twist in the
LOOKDOWN command can cause problems because the LOOKDOWN command doesn’t
make any changes to the index.
value = 167
DEBUG ? value
DEBUG ? index, CR
END
Figure 6-16
Displaying the
Potentiometer’s
Position with the
7-Segment LED
Display
'{$STAMP BS2}
'{$PBASIC 2.5}
OUTH = %00000000
DIRH = %11111111
DO
HIGH 5
PAUSE 100
RCTIME 5, 1, time
LOOKDOWN time, <= [40, 150, 275, 400, 550, 800], index
LOOP
The time variable is then used in a LOOKDOWN table. The LOOKDOWN table decides which
number in the list time is smaller than, then loads the entry number (0 to 5 in this case)
into the index variable.
LOOKDOWN time, <= [40, 150, 275, 400, 550, 800], index
Then, the index variable is used in a LOOKUP table to choose the binary value to load into
the OUTH variable.
LOOKUP index, [ %11100101, %11100001, %01100001,
%00100001, %00000001, %00000000 ], OUTH
SUMMARY
This chapter introduced the 7-segment LED display, and how to read a pin map. This
chapter also introduced some techniques for devices and circuits that have parallel inputs.
The DIRH and OUTH variables were introduced as a means of controlling the values of
BASIC Stamp I/O pins P8 through P15. The LOOKUP and LOOKDOWN commands were
introduced as a means for referencing the lists of values used to display letters and
numbers.
Questions
1. In a 7-segment LED display, what is the active ingredient that makes the display
readable when a microcontroller sends a high or low signal?
2. What is the difference between a schematic symbol and a pin map? How are the
two related?
3. What does common cathode mean? What do you think common anode means?
4. What is the group of wires that conduct signals to and from a parallel device
called?
5. How do the DIRH and OUTH variables work?
6. What are the names of the commands in this chapter that are used to handle lists
of values?
7. What character do you have to type before entering a binary number into the
BASIC Stamp Editor?
8. How do you make the “less than or equal to” comparison?
Exercises
1. Write an OUTH command to set P8, P10, P12 high and P9, P11, P13 low.
Assuming all your I/O pins started as inputs, write the DIRH command that will
cause the I/O pins to send high/low signals while leaving P14, P15 configured as
inputs.
2. Modify one line in SegmentTestWithHighLow.bs2 from Activity #2 so that it
tests a 7-segment LED display connected to P0 through P7. Draw the schematic
of your revised design.
3. Assume that you moved your entire 7-segment LED display circuit so that
instead of being connected to P8 through P15, it is now connected to P0 through
P7. The variable that addresses these I/O pins is OUTL. The L is for low byte
while the H in OUTH is for high byte. Rewrite the LOOKUP command in
DisplayDigitsWithLookup.bs2 so that it addresses the OUTL variable. Rewrite
Chapter #6: Digital Display · Page 183
Projects
1. Spell “FISH CHIPS And dIP” over and over again with your 7-segment LED
display. Make each letter last for 400 ms.
2. Modify DialDisplay.bs2 from Activity #4 so that it causes the 7-segment LED
display to behave as shown in Figure 6-17. The image on the left shows how the
7-segment LED display should look when the potentiometer is centered, with
only segment G emitting light. The middle image in Figure 6-17 shows
segments E and D on. As the potentiometer is turned counterclockwise,
segments E, D, and C turn on in sequence. The rightmost image in Figure 6-17
shows the potentiometer’s knob rotated clockwise of center with segments F and
A on. When the potentiometer’s knob is turned clockwise (from center),
segments F, A, and B should turn on in sequence.
Figure 6-17
Displaying the
Potentiometer’s
Offset from Center
Potentiometer’s knob
in the center position
(left image), rotated
counterclockwise
(middle image), and
rotated clockwise
(right image).
the 7-segment LED display. After entering the two values, press and hold both
buttons briefly to start the timer. The display should show each digit in the time
remaining for ½ second every two seconds. The dot on the display should flash
on and off once per second to let the user know the timer is counting down.
When the timer is done, all LED segments should flash on and off rapidly for 5
seconds.
Further Investigation
As with all texts cited in this section, this one is available for free download from
www.parallax.com.
One example of an every-day device that contains a light sensor is probably your
television. If it can be controlled by a handheld remote, it has a built-in detector for a
type of light called infrared that cannot be seen by the human eye. The handheld remote
uses infrared light to transmit information about the channel, volume, and other keys that
you might press to control the TV. Another common example is a digital camera. A
camera’s light sensors help it adjust for various lighting conditions so that the picture
looks clear regardless of whether it’s a sunny or cloudy day.
Of the light sensors that react to light by changing their resistance, the photoresistor
shown in Figure 7-1 is probably the most common, least expensive and easiest to use. Its
active ingredient is a chemical compound called cadmium sulfide (CdS). This compound
changes resistance depending on how bright the light is that shines on its collecting
surface. Bright light causes low resistance values between the two leads while dim light
causes higher resistance values.
Page 186 · What’s a Microcontroller?
Figure 7-1
Photoresistor Schematic and
Part Drawing.
As with a potentiometer, you can use a photoresistor in an RC-time circuit. The program
to read the photoresistor is also about the same as the one used to read the potentiometer.
Even though the programming is the same, light is very different from rotation or
position. The activities in this chapter focus on applications that use light (instead of
position) to give the microcontroller information. Along the way, some PBASIC
programming techniques will be introduced that will help you with long term data
storage, and with making your programs more manageable and readable.
Although there are two capacitors in the list of parts, you will only use one capacitor in
the circuit at any given time.
decay time is different (P2). Second, the variable resistor is now a photoresistor instead
of a potentiometer.
P2
220 :
0.01 µF
Figure 7-2
Photoresistor RC-time
Circuit Schematic
Vss
P15
P14
P13
P12
P11
P10 Figure 7-3
P9
P8 Wiring Diagram for
P7 Figure 7-2
P6
P5
P4
P3
P2
P1
P0
X2
DO
HIGH 2
PAUSE 100
RCTIME 2, 1, time
DEBUG HOME, "time = ", DEC5 time
LOOP
Modify the circuit by replacing the 0.01 PF capacitor with a 0.1 PF capacitor.
Re-run TestPhotoresistor.bs2 and verify that the RC-time measurements are
roughly ten times their former values.
Chapter #7: Measuring Light · Page 189
Before you move on to the next activity, return the circuit to the original one
shown in Figure 7-2 by removing the 0.1 PF capacitor and replacing it with the
0.01 PF capacitor.
Figure 7-4
Stamp Plot Lite
Graphing
Measured Light
Levels
This graph could depict any number of scenarios to the technician reading it. Perhaps a
microcontroller in a greenhouse switched on the artificial lights after the sunlight dropped
below a certain level. Perhaps a system of motors and gears that maintains a solar
panel’s position for maximum sunlight exposure just readjusted the panel’s position after
Page 190 · What’s a Microcontroller?
detecting a decrease in light exposure. Regardless of the scenario, if you are familiar
with the measurement being graphed, tools like Stamp Plot Lite can really help make
sense out of data. It does this by converting lists of measurements into a graph.
Stamp Plot Lite is free for educational use courtesy of SelmaWare Solutions and can be
installed from the Parallax CD or downloaded from the Parallax web site or directly from
http://www.selmaware.com/.
You can also send display settings to Stamp Plot Lite by sending special messages in
quotes. These messages are called control codes. Control codes are sent to Stamp Plot
Lite at the beginning of a PBASIC program. Although you can click and adjust all the
settings on the software itself, it is usually easier to program the BASIC Stamp to tell
Stamp Plot Lite those settings for you. Here is an example of some configuration settings
Chapter #7: Measuring Light · Page 191
from the next example program that will make your RC-time measurements easier to read
without any adjustments to Stamp Plot Lite’s display settings.
DEBUG "!AMAX 1250", CR,
"!TMAX 25", CR,
"!TMIN 0", CR,
"!SHFT ON", CR,
"!RSET",CR
For more information on how to send values and control codes to Stamp Plot Lite, run
Stamp Pot Lite’s Help file. Click Start, select programs, select Stamp Plot, then click Stamp
Plot Help.
Figure 7-5
Example of Scrolling
Values in the Debug
Terminal.
Make a note of the COM number in the COM Port field in the upper left hand
corner of the Debug Terminal.
Use the Windows Start Menu to run Stamp Plot Lite. Click Start, then select
Programs ĺ Stamp Plot ĺ Stamp Plot Lite.
Set the COM Port field in Stamp Plot Lite to that same value. Figure 7-6 shows
an example where the value is COM1 in the Debug Terminal, so Stamp Plot is
also set to COM1. Your COM port value may be a different number. Just check
to see what the number is in the Debug Terminal, then set Stamp Plot Lite to that
number.
Page 192 · What’s a Microcontroller?
Close the Debug Terminal (click the X button on the top-right or click the Close
button near the bottom of the window).
In the Stamp Plot Lite window, click Connect, then click Plot Data.
Checkmarks should appear in each box after you click it.
Figure 7-6
COM Port Settings
Press and release the Reset button on your Board of Education or HomeWork
Board. This starts the BASIC Stamp’s program over from the beginning, which
sends the DEBUG commands that configure Stamp Plot Lite.
The data will start graphing as soon as you click Plot Data. Hold you hand over
the photoresistor at different distances to simulate different lighting conditions.
Remember, the darker the shadow you cast, the higher the value in the graph; the
brighter the light, the smaller the value.
IMPORTANT: Only one program can use a COM port at one time.
Before attempting to run a different program using the BASIC Stamp Editor, you must
uncheck the Connect and Plot Data checkboxes in Stamp Plot Lite.
Before reconnecting Stamp Plot Lite (by clicking the Connect and Plot Data checkboxes),
you must close the Debug Terminal.
HIGH 2
PAUSE 100
RCTIME 2, 1, time
DEBUG DEC time, CR
LOOP
Experiment with increasing and decreasing these values and note their effects on
the how the graph appears.
If you have difficulty finding your plot, you can always press and release the Reset button
on your Board of Education or BASIC Stamp HomeWork Board to restore the default
settings.
The chip on the BASIC Stamp that stores program memory and data is shown in Figure
7-7. This chip is called an EEPROM. EEPROM stands for electrically erasable
programmable read-only memory. That’s quite a mouthful, and pronouncing each of the
first letters in EEPROM isn’t much better. When people talk about an EEPROM, it is
usually pronounced “E-E-Prom”.
Page 194 · What’s a Microcontroller?
Figure 7-7
EEPROM Chip
on BASIC Stamp
Figure 7-8 shows a window called Memory Map. You can view this window by clicking
Run and selecting Memory Map. The Memory Map uses different colors to show how
both the BASIC Stamp’s RAM (variables) and EEPROM (program memory) are being
used. The Condensed EEPROM Map at the bottom shows that only a small fraction of
the program memory is used to store the photoresistor program from Activity #2. By
scrolling to the bottom of the Detailed EEPROM Map and counting the bytes highlighted
in red, you will find that only 109 bytes out of the 2048 byte EEPROM are used for the
program. The remaining 1939 bytes are free to store data.
Figure 7-8
Memory Map
2048 bytes = 2 KB. You can use 2048 bytes to store 2048 different numbers, each of
which can store a value between 0 and 255.
The upper-case ‘B’ stands for bytes. A lower-case ‘b’ stands for bits. This can make a big
difference because 2048 Kb means that 2048 different numbers, but each number is limited
to a value of either 0 or 1.
Although both the upper case ‘K’ and the lower-case ‘k’ are called kilo, they are slightly
10
different. The upper-case ‘K’ is used to indicate a binary kilobyte, which is 1 × 2 = 1024.
When referring to exactly 2000 bytes, you can use the lower-case k, which stands for kilo (1
3
X 10 = 1000) in the metric system.
Using the EEPROM for data storage can be very useful for remote applications. One
example of a remote application would be a temperature monitor placed in a truck that
hauls frozen food. A second example is a weather monitoring station. One of the pieces
of data a weather station might store for later retrieval is light levels.
Since we are using a photoresistor to measure light levels, this activity introduces a
technique for storing measured light levels to, and retrieving them back from the
EEPROM. In this activity, you will run one PBASIC example program that stores a
series of light measurements in the BASIC Stamp’s EEPROM. After that program is
finished, you will run a second program that retrieves the values from EEPROM and
displays them in the Debug Terminal.
For example, if you want to write the value 195 to address 7 in the EEPROM, you could
use the command:
WRITE 7, 195
Word values can be anywhere between 0 and 65565 while byte values can only contain
numbers between 0 and 255. A word value takes the space of two bytes. If you want to
write a word size value to EEPROM, you have to use the optional Word parameter. Be
careful though. Since a word takes two bytes, you have to skip one of the byte size
Page 196 · What’s a Microcontroller?
addresses in EEPROM before you can write another word. Let’s say you need to save
two word values to EEPROM: 659 and 50012. You could start at address 8, but you will
have to write the second value to address 10.
WRITE 8, Word 659
WRITE 10, Word 50012
Is it possible to write over the program? Yes, and if you do, the program is likely to either
start behaving strangely or stop running altogether. Since the PBASIC program tokens
reside in the highest addresses in the EEPROM, it’s best to use the lowest Address values
for storing numbers with the WRITE command.
How do I know if the Address I’m using is too large? You can use the memory map to
figure out the highest value not used by your PBASIC program. The numbers on the left
side of the Detailed Memory Map shown in Figure 7-8 on page 194 are hexadecimal
numbers, and 792 is the highest value not occupied by a program token. Hexadecimal
means base-16, so 792 is really:
2 1 0
7u16 + 9u16 + 2u16
= 7u256 + 9u16 + 2u1
= 1938.
You can also program the BASIC Stamp to make this conversion for you using the DEBUG
command’s DEC formatter and the $ hexadecimal operator like this:
Gradually increase the shade over the photoresistor during the 2 ½ minute test period for
meaningful data.
PAUSE 1000
The RCTIME command loads the time measurement into the word size time variable.
RCTIME 2, 1, time
The time variable is stored at the address given by the current value of the
eepromAddress variable each time through the loop. Remember, the eepromAddress
variable is incremented by two each time through the loop because a Word variable takes
up two bytes. The address for a WRITE command is always in terms of bytes.
WRITE eepromAddress, Word time
NEXT
While the WRITE command can use either a constant or a variable, the READ command’s
DataItem argument must be a variable, because it has to store the value fetched from the
EEPROM by the READ command.
Let’s say that the variable eepromValueA and eepromValueB are Word variables, and
littleEE is a byte variable. Here are some commands to retrieve the values you stored
using the write command.
READ 7, littleEE
READ 8, Word eepromValueA
READ 10, Word eepromValueB
Compare the table that is displayed by this program with the one displayed by
StoreLightMeasurementsInEeprom.bs2, and verify that the values are the same.
END
The READ command gets the word size value at eepromAddress. This value is loaded
into the time variable.
READ eepromAddress, Word time
The value of the time and eepromAddress variables are displayed as columns in a table
in the Debug Terminal.
DEBUG DEC2 eepromAddress, " ", DEC time, CR
NEXT
1 k:
P15
P14
P13
P12
P11
P10
P9
P8
E C DP G F A B
Vss
P2
220 :
0.01 µF
Vss
Page 202 · What’s a Microcontroller?
P0
P1
P2
P3
P4
P5
P6
P7
P8
P9
P10
P11
P12
P13
P14
P15
X2
X3
Vdd
Figure 7-10
Vin
Wiring Diagram
for Figure 7-9
Vss
Using Subroutines
Most of the programs you have written so far operate inside a DO…LOOP. Since all the
main activity happens inside the DO…LOOP, it is usually called the main routine. As you
add more circuits and more useful functions to your program, it can get kind of difficult
to keep track of all the code in the main routine. Your programs will be much easier to
work with if you organize them into smaller segments of code that do certain jobs.
PBASIC has some commands that you can use to make the program jump out of the main
routine, do a job, and then return right back to the same spot in the main routine. This
will allow you to keep each segment of code that does a particular job somewhere other
than your main routine. Each time you need the program to do one of those jobs, you can
write a command inside the main routine that tells the program to jump to that job, do it,
and come back when the job is done. This process is called executing a subroutine.
Figure 7-11 shows an example of a subroutine and how it’s used. The command GOSUB
Subroutine_Name causes the program to jump to the Subroutine_Name: label. When
the program gets to that label, it keeps running and executing commands until it gets to a
RETURN statement. Then, the program goes back to command that comes after the GOSUB
command. In the case of the example in Figure 7-11, the next command is: DEBUG
"Next command".
Chapter #7: Measuring Light · Page 203
DO
GOSUB Subroutine_Name
DEBUG "Next command"
LOOP
Figure 7-11
How
Subroutines
Subroutine_Name: Work
DEBUG "This is a subroutine..."
PAUSE 3000
RETURN
What’s a label? A label is a name that can be used as a placeholder in your program.
GOSUB is one of the commands you can use to jump to a label. Some others are GOTO,
ON GOTO, and ON GOSUB. You can use these commands to jump to labels. A label must
end with a colon, and for the sake of style, separate words with the underscore character.
When picking a name for a label, make sure not to use a reserved word. The rest of the
rules for a label name are the same as the ones for naming variables listed in the
information box on page 53.
Examine SimpleSubroutines.bs2 and try to guess the order in which the DEBUG
commands will be executed.
Enter and run the program.
Compare the program’s actual behavior with your predictions.
DO
PAUSE 2000
GOSUB First_Subroutine
DEBUG "Back in main.", CR
PAUSE 2000
GOSUB Second_Subroutine
DEBUG "Repeat main...", CR
PAUSE 2000
LOOP
First_Subroutine:
RETURN
Second_Subroutine:
RETURN
What’s a subroutine call? When you use the GOSUB command to make the program jump
to a subroutine, it is called a subroutine call.
Chapter #7: Measuring Light · Page 205
PAUSE 2000
GOSUB First_Subroutine
DEBUG "Back in main.", CR
Figure 7-12
First_Subroutine: First Subroutine
DEBUG " Executing first " Call
DEBUG "subroutine.", CR
PAUSE 3000
RETURN
Figure 7-13 shows a second example of the same process with the second subroutine call
(GOSUB Second_Subroutine).
PAUSE 2000
GOSUB Second_Subroutine
DEBUG "Repeat main...", CR
Make any necessary adjustments to the DEBUG commands so that the display
looks right with all three subroutines.
You can also call one subroutine from within another. This is called nesting subroutines.
Try moving the GOSUB that calls Subroutine_Name into one of the other
subroutines, and see how it works.
When nesting subroutines the rule is no more than four deep. See the BASIC Stamp
Manual for more details. Look up GOSUB and RETURN.
The program that runs the light meter will deal with three different operations:
Each operation is contained within its own subroutine, and the main DO…LOOP routine will
cycle and call each one in sequence, over and over again.
Controlled lighting conditions make a big difference. For best results, conduct this test in
a room lit by fluorescent lights with no direct sunlight (close the blinds). For information on
how to calibrate this meter to other lighting conditions, see the Your Turn section.
GOSUB Get_Rc_Time
GOSUB Delay
GOSUB Update_Display
LOOP
' Subroutines
HIGH 2
PAUSE 3
RCTIME 2, 1, time
RETURN
PAUSE time
RETURN
RETURN
Page 208 · What’s a Microcontroller?
Many programs also have things that need to get done once at the beginning of the
program. Setting all the 7-segment I/O pins low and then making them outputs is an
example. This section of a PBASIC program also has a name, initialization.
This next segment of code is called the main routine. The main routine calls the
Get_Rc_Time subroutine first. Then, it calls the Delay subroutine, and after that, it calls
the Update_Display subroutine. Keep in mind that the program goes through the three
subroutines as fast as it can, over and over again.
DO ' Main routine.
GOSUB Get_Rc_Time
GOSUB Delay
GOSUB Update_Display
LOOP
All subroutines are usually placed after the main routine. The first subroutine’s name is
Get_Rc_Time:, and it takes the RC-time measurement on the photoresistor circuit. This
subroutine has a PAUSE command that charges up the capacitor. The Duration of this
command is small because it only needs to pause long enough to make sure the capacitor
is charged. Note that the RCTIME command sets the value of the time variable. This
variable will be used by the second subroutine.
' Subroutines
Get_Rc_Time: ' RC-time subroutine
HIGH 2
PAUSE 3
RCTIME 2, 1, time
Chapter #7: Measuring Light · Page 209
RETURN
The second subroutine’s name is Delay, and all it contains is a PAUSE command. If you
want to do some extra math on the value of the time variable before using it in the PAUSE
command, it would be appropriate to do that in this subroutine.
Delay:
PAUSE time
RETURN
PAUSE time
to
PAUSE time * 10
Run the modified program and test to make sure the cycling of the 7-segment
LED display is now one tenth of what it was before.
You can also try multiplying the time variable by other values such as 5 or 20,
or dividing by 2 using PAUSE time / 2.
You can also make the display cycle at one tenth the speed by swapping the 0.01PF
capacitor for the 0.1 PF capacitor. Remember that when you use a capacitor that is ten
times as large, the RC-time measurement will become ten times as long.
Which is better, adjusting the software or the hardware? You should always try to use
the best of both worlds. Pick a capacitor that gives you the most accurate measurements
over the widest range of light levels. Once your hardware is the best it can be, use the
software to automatically adjust the light meter so that it works well for the user, both indoors
and outdoors. This takes a considerable amount of testing and refinement, but that’s all part
of the product design process.
Chapter #7: Measuring Light · Page 211
SUMMARY
This chapter introduced a second way to use the RCTIME command by using it to measure
light levels with a photoresistor. Like the potentiometer, the photoresistor is a variable
resistor. Unlike the potentiometer, the photoresistor’s resistance changes with light levels
instead of with position. Stamp Plot Lite was used to graph successive light
measurements, and methods for recording and interpreting graphical data were
introduced. The WRITE and READ commands were used to store and retrieve values to
and from the BASIC Stamp’s EEPROM. The EEPROM was then used in an RC-time
data logging application. In this chapter’s last activity, a light meter application was
developed. This application used subroutines to perform the three different jobs required
for the light meter to function.
Questions
1. What kind of different things can sensors detect?
2. What is the name of the chemical compound that makes a photoresistor sensitive
to light?
3. How is a photoresistor similar to a potentiometer? How is it different?
4. What kind of circuit was used to measure the photoresistor?
5. What kind of measurement does the BASIC Stamp perform on this circuit?
6. How was the photoresistor test circuit different from the potentiometer test
circuit from Chapter #5? What changes had to be made to the photoresistor test
program to get it to work with the new circuit?
7. If the line plotting the photoresistor increases in Stamp Plot Lite, what does that
say about the light level being measured?
8. Can two different programs use the same COM port at the same time?
9. What is the difference between the Span and Time Span settings in Stamp Plot
Lite?
10. What does EEPROM stand for?
11. How many bytes can the BASIC Stamp’s EEPROM store? How many bits can
it store?
12. What command do you use to store a value in EEPROM? What command do
you use to retrieve a value from EEPROM? Which one requires a variable?
13. There are two differences between storing bytes and words using the EEPROM.
What are they?
14. What is a label?
15. What is a subroutine?
Page 212 · What’s a Microcontroller?
Exercises
1. Draw the schematic of a photoresistor RC-time circuit connected to P5.
2. Modify TestPhotoresistor.bs2 to so that it works on a circuit connected to P5
instead of P2.
3. Modify TestPhotoresistor.bs2 so that it displays the same measurements with a
0. 1 PF capacitor that it displays with a 0.01 PF capacitor.
4. Imagine that you are either using a smaller capacitor in your RC-time circuit or
dividing the measurements by a value that always keeps them below 256. This
will allow you to store twice as many values in EEPROM. Explain why.
5. Explain how you would modify LightMeter.bs2 so that the circular pattern
displayed by the 7-segment LED display goes in the opposite direction.
Projects
1. In an earlier chapter, you used a pushbutton to make an LED blink. Instead of
using a pushbutton, use a photoresistor to make the LED blink when you cast a
shadow over it. Hint: You can use an IF…THEN statement and the greater
than/less than operators to decide if your time measurement is above or below a
certain value. The operator > is used for greater than, and the operator < is used
for less than.
2. Use your photoresistor and a PBASIC program to make a simple encoder. An
encoder is a device that reads spokes on a wheel as they pass by. Use your
photoresistor as the sensor that reads the spokes and use your hand as the spokes.
By waving your hand past the photoresistor, you can emulate spokes passing by
the sensor. Use the Debug Terminal to display how many times you pass your
hand over the photoresistor. With some calibration, you can also hold your
fingers wide apart and pass them over the photoresistor to emulate spokes.
3. Design an automated shade controller using a servo and a photoresistor. You
can accomplish this by attaching a piece of cardboard or balsa to your servo
horn. Then, mount the servo above the photoresistor so that the cardboard or
balsa casts a shadow over the photoresistor. The servo should be able to adjust
the level of shade by adjusting the position of the servo horn. Write a program
Chapter #7: Measuring Light · Page 213
that makes the servo move to cast more shade over the photoresistor when the
light is bright and less shade over the photoresistor when the light is dim.
4. Expand the previous project so that it logs the measured light level every half-
minute for 20 minutes, and then displays the measurements in Stamp Plot Lite.
After you get this working, modify the program so that higher light levels are
displayed by high points in the graph while lower light levels are displayed by
lower points in the graph.
Further Investigation
“Applied Sensors”, Student Guide, Version 2.0, Parallax Inc., 2003
More in-depth coverage of light measurement using a photodiode, scientific
units and math, and data logging, are featured in this text along with other sensor
applications.
Figure 8-1
Piezoelectric Speaker
Schematic Symbol and
Part Drawing
Page 216 · What’s a Microcontroller?
Speaker Parts
(1) Piezoelectric speaker
(2) Jumper wires
P15
P14
P13
P12
P11 Figure 8-2
P9 P10 + Piezoelectric
P9
P8 Speaker Circuit
P7 Schematic and
P6
P5
Wiring Diagram
P4
Vss P3
P2
P1
P0
X2
element vibrates, and it causes changes in air pressure just as a guitar string does. As
with the guitar string, your ear detects the changes in air pressure caused by the
piezoelectric speaker, and it typically sounds like a beep or a tone.
As with most of the other commands used in this book, Pin is a value you can use to
choose which BASIC Stamp I/O pin to use. The Duration argument is a value that tells
the FREQOUT command how long the tone should play, in milliseconds. The Freq1
argument is used to set the frequency of the tone, in Hertz. There is an optional Freq2
argument that can be used to mix frequencies.
Here is how to send a tone to I/O pin P9 that lasts for 1.5 seconds and has a frequency of
2 kHz:
FREQOUT 9, 1500, 2000
'{$STAMP BS2}
'{$PBASIC 2.5}
1. Pause
2. Duration
3. Frequency
The pause is the time between tones, and you can use the PAUSE command to create that
pause. The duration is the amount of time a tone lasts, which you can set using the
FREQOUT command’s Duration argument. The frequency determines the pitch of the
tone. The higher the frequency, the higher the pitch, the lower the frequency, the lower
the pitch. This is, of course, determined by the FREQOUT command’s Freq1 argument.
'{$STAMP BS2}
'{$PBASIC 2.5}
DEBUG "Alarm...", CR
PAUSE 100
FREQOUT 9, 500, 1500
PAUSE 500
FREQOUT 9, 500, 1500
PAUSE 500
FREQOUT 9, 500, 1500
PAUSE 500
FREQOUT 9, 500, 1500
PAUSE 500
DEBUG "Hyperspace...", CR
PAUSE 100
FOR duration = 15 TO 1 STEP 1
FOR frequency = 2000 TO 2500 STEP 20
FREQOUT 9, duration, frequency
NEXT
NEXT
DEBUG "Done", CR
END
The “Hyperspace” routine uses no delay, but it varies both the duration and frequency.
By using FOR…NEXT loops to rapidly change the frequency and duration, you can get
some interesting sound effects. When one FOR…NEXT loop executes inside another one, it
is called a nested loop. Here is how the nested FOR…NEXT loop shown below works. The
Page 220 · What’s a Microcontroller?
duration variable starts at 15, then the frequency loop takes over and sends
frequencies of 2000, then 2020, then 2040, and so on, up through 2500 to the piezo
speaker. When the frequency loop is finished, the duration loop has only repeated one
of its 15 passes. So it subtracts one from the value of duration and repeats the
frequency loop all over again.
FOR duration = 15 TO 1
FOR frequency = 2000 TO 2500 STEP 15
FREQOUT 9, duration, frequency
NEXT
NEXT
'{$STAMP BS2}
'{$PBASIC 2.5}
END
Chapter #8: Frequency and Sound · Page 221
You can use the optional Freq2 argument to mix two frequencies using the FREQOUT
command. For example, you can mix 2 and 3 kHz together like this:
FREQOUT 9, 1000, 2000, 3000
Each touchtone keypad tone is also an example of two frequencies mixed together. In
telecommunications, that is called DTMF (Dual Tone Multi Frequency). There is also a
PBASIC command called DTMFOUT that is designed just for sending phone tones. For
examples of projects where phone numbers are dialed, see the DTMFOUT command in the
BASIC Stamp Manual.
Beat is when two tones very close in frequency are played together causing the tone you
hear to fade in and out. The frequency of that fading in and out is the difference between
the two frequencies. If the difference is 1 Hz, the tone will fade in and out at 1 Hz. If the
difference is 2 Hz, the tone will fade in and out at 2 Hz.
The variations in air pressure made by the piezoelectric speaker are called sound waves.
When the tone is loudest, the variations in air pressure caused by the two frequencies are
adding to each other (called superposition). When the tone is at its quietest, the variations
in air pressure are canceling each other out (called interference).
'{$STAMP BS2}
'{$PBASIC 2.5}
DEBUG "Done", CR
END
Chapter #8: Frequency and Sound · Page 223
Internet search for – “musical scale”: By using the words "musical scale" in a search
engine like Google or Yahoo, you will find lots of fascinating information about the history,
physics and psychology of the subject. The 12 note scale is the main scale of western
music. Other cultures use scales that contain 2 to 35 notes per octave.
If you’ve ever heard a singer practice his/her notes by singing the Solfege, “Do Re Mi Fa
Sol La Ti Do”, the singer is attempting to match the notes that you get from striking the
white keys on a piano keyboard. These white keys are called natural keys. A black key
on a piano can either be called sharp or flat. For example, the black key between the C
and D keys is either called C-sharp (C#) or D-flat (Db). Whether a key is called sharp or
flat depends on the particular piece being played, and the rules for that are better left to
the music classes.
Page 224 · What’s a Microcontroller?
Figure 8-3
Rightmost Piano Keys and Their Frequencies
1244.5
1480.0
1661.2
1864.7
1217.5
2489.0
2960.0
3322.4
3729.3
1108.7
3520.0
3951.1
4186.0
1046.5
1318.5
1396.9
1568.0
1760.0
1975.5
2093.0
2349.3
2637.0
2793.0
3136.0
1174.7
C D F G A C D F G A
6 6 6 6 6 7 7 7 7 7
# # # # # # # # # #
or or or or or or or or or or
D E G A B D E G A B
6 6 6 6 6 7 7 7 7 7
b b b b b b b b b b
C6 D6 E6 F6 G6 A6 B6 C7 D7 E7 F7 G7 A7 B7 C8
Tuning Method: The keyboard in Figure 8-3 uses a method of tuning called equal
temperament. The frequencies are determined using a reference note, then multiplying it by
(n/12)
2 for values of n = 1, 2, 3, etc. For example, you can take the frequency for A6, and
(1/12) (2/12)
multiply by 2 to get the frequency for A6#. Multiply it by 2 to get the frequency for
B6, and so on. Here is an example of calculating the frequency for B6 using A6 as a
reference frequency:
The frequency of A6 is 1760
(2/12)
2 = 1.1224
1760 X 1.224 = 1975.5
1975.5 is the frequency of B6
music using any other musical instrument. These rules apply to the same elements that
were used to make sound effects, frequency, duration, and pause. This next example
program plays some of the musical note frequencies on the piezospeaker, each with a
duration of half a second.
'{$STAMP BS2}
'{$PBASIC 2.5}
END
Here is an example of how to use the DATA directive to store the characters that
correspond to musical notes.
You can use the READ command to access these characters. The letter ‘C’ is located at
address Notes + 0, and a second letter ‘C’ is located at Notes + 1. Then, there’s a
letter ‘G’ at Notes + 2, and so on. For example, if you want to load the last letter ‘G’
into a byte variable called noteLetter, use the command:
Characters are stored in bytes. Each character has a number-code that is used to store it.
These codes are called ASCII codes, and they were introduced in Chapter #1. These
values can range anywhere from 0 to 255.
It takes more than one byte to store a value greater than 255. The word variable takes
two bytes of space in memory, and a word variable can store a number between 0 and
65535.
You can also store lists of numbers using the DATA directive. Frequency and duration
values that the BASIC Stamp uses for musical notes need to be stored in word variables
because they are usually greater than 255. Here is how to do that with a DATA directive.
Frequencies DATA Word 2093, Word 2093, Word 3136, Word 3136,
Word 3520, Word 3520, Word 3136
Because each of these values occupies two bytes, accessing them with the read command
is different from accessing characters. The first 2093 is at Frequencies + 0, but the
second 2093 is located at Frequencies + 2. The first 3136 is located at Frequencies
+ 4, and the second 3136 is located at Frequencies + 6.
Chapter #8: Frequency and Sound · Page 227
The values in the Frequencies DATA directive correspond with the musical notes in
the Notes DATA directive.
Here is a FOR…NEXT loop that places the Notes DATA into a variable named noteLetter,
then it places the Frequencies DATA into a variable named noteFreq.
FOR index = 0 to 6
READ Notes + index, noteLetter
READ Frequencies + (index * 2), Word noteFreq
DEBUG noteLetter, " ", DEC noteFreq, CR
NEXT
What does the (index * 2) do? Each value stored in the Frequencies DATA directive
takes a word (two bytes), while each character in the Notes DATA directive only takes
one byte. The value of index increases by one each time through the FOR…NEXT loop.
That’s fine for accessing the note characters using the command READ Notes +
index, noteLetter. The problem is that for every one byte in Notes, the index
variable needs to point twice as far down the Frequencies list. The command READ
Frequencies + (index * 2), Word noteFreq, takes care of this.
The next example program stores notes and durations using DATA, and it uses the
FREQOUT command to play each note frequency for a specific duration. The result is the
first few notes from the children’s song Twinkle Twinkle Little Star.
The Alphabet Song used by children to memorize their “ABCs” uses the same notes as
Twinkle Twinkle Little Star.
'{$STAMP BS2}
'{$PBASIC 2.5}
Frequencies DATA Word 2093, Word 2093, Word 3136, Word 3136,
Word 3520, Word 3520, Word 3136
Durations DATA Word 500, Word 500, Word 500, Word 500,
Word 500, Word 500, Word 1000
FOR index = 0 TO 6
NEXT
END
Modify TwinkleTwinkle.bs2 so that it plays the first two phrases of the song
instead of just the first phrase.
Rests are the time between notes when no tones are played. Rest durations are also
measured as whole, half, quarter, eighth, sixteenth and thirty-second.
Here is an example of the DATA directives that stores musical notes and durations for the
next example program. When played, it should resemble the song “Frere Jacques”. Only
the note characters are stored in the Notes DATA directive because LOOKUP and
LOOKDOWN commands will be used to match up letters to their corresponding frequencies.
Durations DATA 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
2, 4, 4, 2
The first number in the Durations DATA directive tells the program how long the first
note in the Notes Data directive should last. The second duration is for the second note,
Page 230 · What’s a Microcontroller?
and so on. The durations are no longer in terms of milliseconds. Instead, they are much
smaller numbers that can be stored in bytes, so there is no Word prefix in the data
directive. Compared to storing values in terms of milliseconds, these numbers are more
closely related to sheet music. Here is a list of what each duration means.
x 1 – whole note
x 2 – half note
x 4 – quarter note
x 8 – eighth note
x 16 – sixteenth note
x 32 – thirty-second note
After each value is read from the Durations DATA directive, it is divided into the
WholeNote value to get the Duration used in the FREQOUT command. The amount of
time each note lasts depends on the tempo of the song. A faster tempo means each note
lasts for less time, while a slower tempo means each note lasts longer. Since all the note
durations are fractions of a whole note, you can use the duration of a whole note to set the
tempo.
What does the "Q" in Notes DATA mean? "Q" is for quit, and a DO WHILE…LOOP
checks for "Q" each time through the loop.
How do I play a rest? You can insert a rest between notes by inserting a "P". The Your
th
Turn section has the first few notes from Beethoven’s 5 Symphony, which has a rest in it.
How do I play sharp/flat notes? NotesAndDurations.bs2 has values in its lookup tables for
sharp/flat notes. When you use the lower-case version of the note, it will play the flat note.
For example, if you want to play B-flat, use “b” instead of “B”. Remember that this is the
same frequency as A-sharp.
'{$STAMP BS2}
'{$PBASIC 2.5}
"G","E","F","G","Q"
Durations DATA 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
2, 4, 4, 2
index = index + 1
LOOP
END
The declarations for the five variables used in the program are shown below. Even
though a FOR…NEXT loop is no longer used to access the data, there still has to be a
variable (index) that keeps track of which DATA entry is being read in Notes and
Durations. The offset variable is used in the LOOKDOWN and LOOKUP commands to
Page 232 · What’s a Microcontroller?
select a particular value. The noteLetter variable stores a character accessed by the
READ command. LOOKUP and LOOKDOWN commands are used to convert this character into
a frequency value. This value is stored in the noteFreq variable and used as the
FREQOUT command’s Freq1 argument. The noteDuration variable is used in a READ
command to receive a value from the Durations DATA. It is also used to calculate the
Duration used in the FREQOUT command.
index VAR Byte
offset VAR Nib
The main loop keeps executing until the letter ‘Q’ is read from the Notes DATA.
DO UNTIL noteLetter = "Q"
A READ command gets a character from the Notes DATA, and stores it in the noteLetter
variable. The noteLetter variable is then used in a LOOKDOWN command to set the value
of the offset variable. Remember that offset stores a 1 if “b” is detected, a 2 if “B” is
detected, a 3 if “C” is detected, and so on. This offset value is then used in a LOOKUP
command to figure out what the value of the noteFreq variable should be. If offset is
1, noteFreq will be 1865, if offset is 2, noteFreq will be 1976, if offset is 3,
noteFreq is 2093, and so on.
READ Notes + index, noteLetter
The note’s frequency has been determined, but the duration still has to be figured out.
The READ command uses the value of index to place a value from the Durations DATA
into noteDuration.
READ Durations + index, noteDuration
Chapter #8: Frequency and Sound · Page 233
Now that noteDuration and noteFreq are determined, the FREQOUT command plays the
note.
FREQOUT 9, noteDuration, noteFreq
Each time through the main loop, the index value must be increased by one. When the
main loop gets back to the beginning, the first thing the program does is read the next
note, using the index variable.
index = index + 1
LOOP
Entering musical data is much easier when all you have to do is record notes and
durations. Here are the first eight notes from Beethoven’s Fifth Symphony.
Notes DATA "G","G","G","e","P","F","F","F","D","Q"
Durations DATA 8, 8, 8, 2, 8, 8, 8, 8, 2
The term “dotted” refers to a dot used in sheet music to indicate that a note should be
played 1 ½ times as long as its normal duration. For example, a dotted quarter note
should last for the duration of a quarter note, plus an eighth note. A dotted half note lasts
for a half plus a quarter note’s duration. You can add a data table that stores whether or
not a note is dotted. In this example, a zero means there is no dot while a 1 means there
is a dot:
Dots DATA 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 1, 0
Cell phones typically take the tempo for a song in beats per minute. This is the same as
saying quarter notes per minute.
BeatsPerMin CON 200
Figure 8-4 is a repeat of Figure 8-3 from page 224. It shows the 6th and 7th octaves on the
piano keyboard. These are the two octaves that sound the clearest when played by the
piezospeaker. Here is an example of a DATA directive you will use in the Your Turn
section to play notes from more than one octave using the Notes DATA directive.
Octaves DATA 6, 7, 6, 6, 6, 6, 6, 6, 6, 7, 6,
6, 6, 6
Chapter #8: Frequency and Sound · Page 235
Figure 8-4
Rightmost Piano Keys and Their Frequencies
1244.5
1480.0
1661.2
1864.7
1217.5
2489.0
2960.0
3322.4
3729.3
1108.7
3951.1
4186.0
2093.0
2349.3
2637.0
2793.0
3136.0
3520.0
1046.5
1318.5
1396.9
1568.0
1760.0
1975.5
1174.7
C D F G A C D F G A
6 6 6 6 6 7 7 7 7 7
# # # # # # # # # #
or or or or or or or or or or
D E G A B D E G A B
6 6 6 6 6 7 7 7 7 7
b b b b b b b b b b
C6 D6 E6 F6 G6 A6 B6 C7 D7 E7 F7 G7 A7 B7 C8
'{$STAMP BS2}
'{$PBASIC 2.5}
Page 236 · What’s a Microcontroller?
index = index + 1
LOOP
Chapter #8: Frequency and Sound · Page 237
END
In the previous example program, WholeNote was a constant. This time, it’s a variable
that will hold the duration of a whole note in ms. After this value is calculated,
WholeNote will be used to determine all the other note durations, just like in the previous
program. The index, offset, noteLetter, and noteDuration variables are also used
in the same manner they were in the previous program. The noteFreq variable is
handled a little differently since now it has to be adjusted depending on the octave the
note is played in. The noteOctave and noteDot variables have been added to handle
the octave and dot features.
wholeNote VAR Word
The wholeNote variable is calculated using the BeatsPerMin. The tempo of the song is
defined in beats per minute, and the program has to divide BeatsPerMin into 60000 ms,
then multiply by 4. The result is the correct value for a whole note.
wholeNote = 60000 / BeatsPerMin * 4
Now that octaves are in the mix, the part of the code that figures out the note frequency
has changed. The LOOKUP command’s table of values contains note frequencies from the
8th octave. These values can be divided by 1 if you want to play notes in the 8th octave,
by 2 if you want to play notes in the 7th octave, by 4 if you want to play notes in the 6th
octave and by 8 if you want to play notes in the 5th octave. The division happens next.
All this LOOKUP command does is place a note from the 8th octave into the noteFreq
variable.
LOOKUP offset, [ 4186, 4435, 4699, 4978, 5274,
5588, 5920, 6272, 6645, 7040,
7459, 7902, 0, 0 ], noteFreq
Here is how the noteFreq variable is adjusted for the correct octave. First, the READ
command grabs the octave value stored in the Octaves DATA. This could be a value
between 5 and 8.
READ Octaves + index, noteOctave
that value from 8. If noteOctave was 8, now it’s 0. If noteOctave was 7, now it’s 1.
If noteOctave was 6, now it’s 2, and if noteOctave was 5, now it’s 3.
noteOctave = 8 - noteOctave
Now, noteOctave is a value that can be used as an exponent of 2, but how do you raise 2
to a power in PBASIC? One answer is to use the DCD operator. DCD 0 is 1, DCD 1 is 2,
DCD 2 is 4, and DCD 3 is 8. Dividing noteFreq by DCD noteOctave means you are
dividing by 1, 2, 4, or 8, which divides noteFreq down by the correct value. The end
result is that noteFreq is set to the correct octave. You will use the Debug Terminal in
the Your Turn section to take a closer look at how this works.
noteFreq = noteFreq / (DCD noteOctave)
How am I supposed to know to use the DCD operator? Keep learning and practicing.
Every time you see a new command, operator, or any other keyword used in an example,
look it up in the BASIC Stamp manual. Read about it, and try using it in a program of your
own design. Get in the habit of periodically reading the BASIC Stamp Manual and trying the
short example programs. That’s the best way to get familiar with the various commands and
operators and how they work. By doing these things, you will develop a habit of always
adding to the list of programming tools you can use to solve problems.
The first two lines of code for determining the note duration are about the same as the
code from the previous example program. Now, however, any note could be dotted,
which means the duration might have to be multiplied by 1.5. A READ command is used
to access values stored in EEPROM by the Dots DATA directive. An IF…THEN statement is
used to multiply by 3 and divide by 2 whenever the value of the noteDot variable is 1.
READ Durations + index, noteDuration
noteDuration = WholeNote / noteDuration
Integer math The BASIC Stamp does not automatically process a number like 1.5. When
performing math, it only works with integers: …, -5, -4, -3, -2, -1, 0, 1, 2, 3, … The best
solution for multiplying by 1.5 is to multiply by 3/2. First, multiply by 3, and then divide by 2.
There are many ways to program the BASIC Stamp to handle fractional values. You can
program the BASIC Stamp to use integers to figure out the fractional portion of a number.
This is introduced in the Basic Analog and Digital Student Guide. There are also two
operators that make fractional values easier to work with, and they are: ** and */. These
are explained in detail in the Applied Sensors Student Guide and in the BASIC Stamp
Manual.
Page 240 · What’s a Microcontroller?
The remainder of this example program works the same way that it did in the previous
example program:
FREQOUT 9, noteDuration, noteFreq
index = index + 1
LOOP
END
Those two notes in the 7th octave are essential for making the tune sound right. It’s
interesting to hear what happens if those 7 values are changed to 6.
Try changing the two 7 values in the Octaves DATA directive so that they are 6.
Keep in mind, this will make “Take Me out to the Ball Game” sound weird.
Run the program, and listen to the effect of the wrong octaves on the song.
Change the Octaves DATA back to its original state.
Chapter #8: Frequency and Sound · Page 241
Run the program again and listen to see if it sounds correct again.
One of the most widely used way of composing, recording and posting notes is one that
features strings of text that describe each note in the song. Here is an example of how the
first few notes from Beethoven’s 5th look in RTTTL format:
Beethoven5:d=8,o=7,b=125:g,g,g,2d#,p,f,f,f,2d
This format for storing musical data is called RTTTL, which stand for Ringing Tone Text
Transfer Language. The great thing about RTTTL files is that they are widely shared via
the World Wide Web. Many sites have RTTTL files available for free download. There
are also free software programs that can be used to compose and emulate these files as
well as download them to your cell phone. The RTTTL specification is also published on
the World Wide Web. Appendix G summarizes how an RTTTL file stores notes,
durations, pauses, tempo, and dotted notes.
This activity introduces some PBASIC programming techniques that can be used to
recognize different elements of text. The ability to recognize different characters or
groups of characters and take action based on what those characters contain is extremely
useful. In fact, it’s the key to converting RTTTL format ringtone (like Beethoven5
above) into music. At the end of this activity, there is an application program that you
can use to play RTTTL format ringtones.
SELECT expression
CASE condition(s)
statement(s)
ENDSELECT
You can try the next two example programs to see how SELECT…CASE works.
SelectCaseWithValues.bs2 takes numeric values you enter into the Debug Terminal and
it tells you the minimum variable size you will need to hold that value.
SelectCaseWithCharacters.bs2 tells you whether the character you entered into the Debug
Terminal is upper or lower case, a digit, or punctuation.
Remember to use the upper Windowpane in the Debug Terminal to transmit the
characters you type to the BASIC Stamp. The Transmit and Receive Windowpanes are
shown in Figure 8-5.
Table 2-2 (below) is a copy of the table on page 54. Use this table to verify that
the example program makes the right decisions about the size of the numbers
you enter into the Debug Terminal.
What happens if you enter a number larger than 65535? If you enter the number 65536,
the BASIC Stamp will store the number 0. If you enter the number 65537, the BASIC Stamp
will store the number 1, and so on. When a number is too large for the variable it fits into, it
is called overflow.
'{$STAMP BS2}
'{$PBASIC 2.5}
DO
SELECT value
CASE 0, 1
DEBUG "Bit", CR
PAUSE 100
CASE 2 TO 15
DEBUG "Nib (Nibble)", CR
PAUSE 200
CASE 16 TO 255
DEBUG "Byte", CR
PAUSE 300
Page 244 · What’s a Microcontroller?
ENDSELECT
LOOP
The DEBUGIN command takes the number you enter and places it into the value variable.
DEBUGIN DEC value
The SELECT statement chooses the value variable as the one to evaluate cases for.
SELECT value
The first case is if the value variable equals either 0 or 1. If value equals either of those
numbers, the DEBUG and PAUSE commands that follow it are executed.
CASE 0, 1
DEBUG "BIT", CR
PAUSE 100
The second case is if value equals any number from 2 to 15. If it does equal any of
those numbers, the DEBUG and PAUSE commands below it are executed.
CASE 2 to 15
DEBUG "NIB (Nibble)", CR
PAUSE 200
When all the cases are done, the ENDSELECT keyword is used to complete the
SELECT..CASE statement.
ENDSELECT
some punctuation. If you enter a character the program does not recognize, it will tell
you to try again (entering a different character).
'{$STAMP BS2}
'{$PBASIC 2.5}
DO
DEBUGIN character
SELECT character
CASE ELSE
DEBUG CR, "Character not known.", CR,
"Try a different one."
ENDSELECT
LOOP
Page 246 · What’s a Microcontroller?
The quotation marks are used to tell the BASIC Stamp Editor that you are referring to
characters.
SELECT character
There is also one different CASE statement that was not used in the previous example:
CASE ELSE
DEBUG CR, "Character not known.", CR,
"Try a different one."
This CASE statement tells the SELECT code block what to do if none of the other cases are
true. You can get this case to work by entering a character such as % or $.
Turn section. This program plays a tune called Reveille, which is the bugle call played at
military camps first thing in the morning. You may have heard it in any number of
movies or television shows.
RTTTL_File DATA "Reveille:d=4,o=7,b=140:8g6,8c,16e,16c,8g6,8e,",
"8c,16e,16c,8g6,8e,8c,16e,16c,8a6,8c,e,8c,8g6,",
"8c,16e,16c,8g6,8e,8c,16e,16c,8g6,8e,8c,16e,",
"16c,8g6,8e,c,p,8e,8e,8e,8e,g,8e,8c,8e,8c,8e,8c,",
"e,8c,8e,8e,8e,8e,8e,g,8e,8c,8e,8c,8g6,8g6,c."
'{$STAMP BS2}
'{$PBASIC 2.5}
RETURN
RETURN
RETURN
' -----[ Subroutine - Check For '.' Indicating 1.5 Duration ]-------------
Chapter #8: Frequency and Sound · Page 251
RETURN
RETURN
If you examine the code briefly, you might notice that you have already used all of the
commands and operators in the program. Here is a list of the elements in this application
example that should, by now, be familiar:
Only one RTTTL_File DATA directive at a time! Make sure to replace, not add, your
new RTTTL_File DATA directive.
Downloading RTTTL Files: As mentioned earlier, there are lots of RTTTL files available
for download from various sites on the World Wide Web. These files are contributed by ring-
tone enthusiasts, many of whom are not music experts. Some phone tones are pretty good,
others are barely recognizable.
If you want to download and play some more RTTTL files, make sure to remove any spaces
from between characters, then insert the text file between quotes.
Chapter #8: Frequency and Sound · Page 253
SUMMARY
This chapter introduced techniques for making sounds and musical tones using the
BASIC Stamp and a piezoelectric speaker. The FREQOUT command can be used to send a
piezoelectric speaker high/low signals that cause it to make sound effects and/or musical
notes. The FREQOUT command has arguments that control the I/O Pin the signal is sent
to, the Duration of the tone, the frequency of the tone (Freq1). The optional Freq2
argument can be used to mix tones.
Sound effects can be made by adjusting the frequency and duration of tones and the
pauses between. The value of the frequency can also be swept across a range of values or
mixed to create a variety of effects.
Making musical notes also depends on frequency, duration, and pauses. The value of the
FREQOUT command’s Duration argument is determined by the tempo of the song and the
duration of the note (whole, half, quarter, etc.). The Freq1 value of the note is
determined by the note’s letter and octave. Rests between notes are used to set the
duration of the PAUSE command.
Playing simple songs using the BASIC Stamp can be done with a sequence of FREQOUT
commands, but there are better ways to store and retrieve musical data. DATA directives
along with their optional Symbol labels were used to store byte values using no prefix
and word values using the Word prefix. The READ command was used to retrieve values
stored by DATA directives. The READ command’s Address argument always used the
DATA directive’s optional Symbol label to differentiate between different types of data.
Some the symbol labels that were used were Notes, Durations, Dots, and Octaves.
Musical data can be stored in formats that lend themselves to translation from sheet
music. The sheet music style data can then be converted into Frequency using the
LOOKUP and LOOKDOWN commands. Mathematic operations can also be performed on
variable values to change the octave of a note by dividing its frequency by a power of
two. Mathematic operations are also useful for note durations given either the tempo or
the duration of a whole note.
need to be taken based on the variable’s value. A program that converts strings of
characters that describe musical tones for cell phones (called RTTTL files) was used to
introduce a larger program that makes use of all the programming techniques introduced
in this text. SELECT…CASE played a prominent role in this program because it is used to
examine characters selected in an RTTTL file on a case-by-case basis.
Questions
1. What causes a tone to sound high-pitched? What causes a tone to sound low-
pitched?
2. What does FREQOUT 15, 1000, 3000 do? What effect does each of the
numbers have?
3. What are the three main elements of sound effects?
4. Can you put one FOR…NEXT loop inside another? How does that work?
5. How can you modify the FREQOUT command from Question 2 so that it sends
two frequencies at once?
6. If you strike a piano’s B6 key, what frequency does it send?
7. How can you use the FREQOUT command to send musical notes?
8. Where does the data in a DATA directive get stored?
9. How much memory does it take to store a character?
10. How much memory is a word?
11. How do you modify a DATA directive or READ command if you want to store and
retrieve word values?
12. Can you have more than one DATA directive? If so, how would you tell a READ
command to get data from one or the other DATA directive?
13. Trick question: How long does a quarter note last?
14. What commands can you use to translate note letters (characters) in a DATA
directive into their corresponding frequencies?
15. What’s an octave? If you know the frequency of a note in one octave, what do
you have to do to that frequency to play it in the next higher octave?
16. What’s tempo? How do you figure out the value of a quarter note from the
tempo? How do you figure out the value of a whole note?
17. What does the DCD operator do? What’s DCD 3? What’s DCD 4? What’s DCD
5?
18. What does SELECT…CASE do?
Chapter #8: Frequency and Sound · Page 255
Exercises
1. Modify the “Alarm…” tone from ActionTones.bs2 so that the frequency of the
tone it plays increases by 500 each time the tone repeats.
2. Modify NestedLoops.bs2 so that the FREQOUT command’s Freq2 argument also
uses the value of the duration variable.
3. Modify DoReMiFaSolLaTiDo.bs2 so that it plays all the notes in the octave
from C5 through C6.
4. Modify the DEBUG commands in TwinkleTwinkle.bs2 so that it displays the
duration of each note as either quarter (a duration of 500) or half (a duration or
1000).
5. Modify NotesAndDurations.bs2 so that it calculates the value of a variable called
wholeNote based on the value of a constant called Tempo.
6. Explain how you would modify MusicWithMoreFeatures.bs2 so that it plays two
frequencies at the same time for each note.
7. Explain how to modify MusicWithMoreFeatures.bs2 so that it displays an alert
message in the Debug Terminal each time a dotted note is played.
8. Explain what the CheckForDot subroutine in MicroMusicWithRtttl.bs2 does.
How does it convert a note into a dotted note?
Projects
1. Build pushbutton controlled tone generator. If one pushbutton is pressed, the
speaker should make a 2 kHz beep for 1/5 of a second. If the other pushbutton is
pressed the speaker should make a 3 kHz beep for 1/10 of a second.
2. Modify the program from the first project so that each time you press and release
one of the pushbuttons, it plays a musical note for ½ a second. If you press one
pushbutton, the note should advance up to the next higher note. If you press the
other pushbutton, it should play the next lower note.
3. Use a potentiometer circuit to control the tempo of TwinkleTwinkle.bs2.
4. Make an application that generates tone based on the brightness in a room. You
will need a photoresistor circuit for this application. The speaker should beep
once every second. The tone should get higher as the light gets brighter and
lower as the light gets dimmer.
5. Make a musical note player. A potentiometer is used to select the note, and the
pushbutton plays the note. Optionally, use two pushbuttons. If both pushbuttons
are pressed, it plays a half note. If one pushbutton is pressed, it plays a quarter
note, and if the other pushbutton is pressed, it plays an eighth note.
Page 256 · What’s a Microcontroller?
Further Investigation
“Basic Analog and Digital”, Student Guide, Version 2.0, Parallax Inc., 2003
The speaker is used to make a frequency generated by a device called a 555
timer audible. The BASIC Stamp is used to measure the frequency of the tone
with a command called COUNT.
Figure 9-1
Integrated
Circuits on the
BASIC Stamp
Page 258 · What’s a Microcontroller?
People use the term “integrated circuit” (IC) to talk about little black chips. The
integrated circuit is actually a tiny silicon chip that’s contained inside the black plastic or
ceramic case. Depending on the chip, it may have anywhere between hundreds and
millions of transistors. A transistor is the basic building block for integrated circuits, and
you will have the opportunity to experiment with a transistor in this chapter. Other
familiar components that are designed into silicon chips include diodes, resistors and
capacitors.
Take a moment to think about the activities you’ve tried in this book so far. The list
includes switching LEDs on and off, reading pushbuttons, controlling servos, reading
potentiometers, measuring light, controlling displays, and making sounds. Even though
that’s just the beginning, it’s still pretty impressive, especially considering that you can
combine these activities to make more complex gizmos and gadgets. The core of the
system that made all those activities possible is comprised of just the three integrated
circuits shown in Figure 9-1 and a few other parts. It just goes to show how powerful
integrated circuits can be when they are designed to work together.
In this chapter, you will experiment with a transistor, and a special-purpose integrated
circuit called a digital potentiometer. As mentioned earlier, the transistor is the basic
building block for integrated circuits. It’s also a basic building block for lots of other
circuits as well. The digital potentiometer also has a variety of uses. Keep in mind that
for each activity you have done, there are probably hundreds of different ways that you
could use each of these integrated circuits.
Chapter #9: Electronic Building Blocks · Page 259
C Figure 9-2
B
B 2N3904 Transistor
E
2N3904
E
(1) Potentiometer – 10 k:
(3) Jumper wires
What’s the difference between this and connecting an LED circuit to an I/O pin?
BASIC Stamp I/O pins have limitations on how much current they can deliver. Transistors
have limitations too, but they are much higher. In the Industrial Control Student Guide, a
transistor is used to drive a small DC fan. It is also used to supply large amounts of current
to a small resistor that is used as a heating element. Either of these two applications would
draw so much current that they would quickly damage the BASIC Stamp, but the transistor
takes it in stride.
Part Substitutions: It is sometimes necessary for Parallax to make a part substitution. The
part will function the same, but the label on it may be different. If you find that the digital
potentiometer included in your What’s a Microcontroller Parts Kit is not labeled AD5220, rest
assured that it will still work the same way and perform correctly in this activity.
Reference
Notch Figure 9-5
AD5220 Pin Map
1. CLK – The pin that receives clock pulses (low-high-low signals) to move the
wiper terminal.
2. U/D – The pin that receives a high signal to make the wiper (W1) terminal move
towards A1, and a low signal to make it move towards B1. This pin just sets the
direction, the wiper terminal doesn’t actually move until a pulse (a low – high –
low signal) is sent to the CLK pin.
3. A1 – The potentiometer’s A terminal.
4. GND – The ground connection. The ground on the Board of Education and
BASIC Stamp HomeWork Board is the Vss terminal.
5. W1 – The potentiometer’s wiper (W) terminal.
Chapter #9: Electronic Building Blocks · Page 263
The AD5220 Part Datasheet: To see the part datasheet for the AD5220: Go to
www.analog.com. Enter AD5220 into the Search field on Analog Devices’ home page, and
click the Search button. Click the Data Sheets link. Click the link that reads “AD5220:
Increment/Decrement Digital Potentiometer Datasheet”.
Vdd Vdd
Vdd
AD5220
CLK Vdd 8
P6 1
P5 2
U/D CS 7 Figure 9-6
Digital Potentiometer
A1 B1 6
3
Controlled Transistor
4
GND W1 5 100 k: Circuit Schematic
100 k:
Vss Vss
Page 264 · What’s a Microcontroller?
AD5220
P5
P4
P3
P2
P1
P0
X2
Let’s say you turn the potentiometer’s knob one step clockwise. The LED will get only
slightly brighter. This would be the same as sending a high signal to the AD5220’s U/D
pin and sending one pulse (high-low-high) to the CLK pin.
HIGH 5
PULSOUT 6, 1
Imagine next that you turn your manual potentiometer 3 steps counterclockwise. The
LED will get a little bit dimmer. This would be the same as sending a low signal to the
U/D pin on the AD5220 and sending three pulses to the CLK pin.
LOW 5
FOR counter = 1 TO 3
PULSOUT 6, 1
PAUSE 1
NEXT
Chapter #9: Electronic Building Blocks · Page 265
Imagine next that you turn the potentiometer all the way clockwise. That’s the same as
sending a high signal to the AD5220’s U/D pin and sending 65 pulses to the CLK pin.
Now the LED should be shining brightly.
HIGH 5
FOR counter = 1 TO 65
PULSOUT 6, 1
PAUSE 1
NEXT
Finally, imagine that you turn your manual potentiometer all the way counterclockwise.
The LED should emit no light. That’s the same as sending a low signal to the U/D pin,
and applying 128 pulses to the CLK pin
LOW 5
FOR counter = 0 TO 127
PULSOUT 6, 1
PAUSE 1
NEXT
DO
LOW 5
HIGH 5
PULSOUT 6, 1
PAUSE 10
NEXT
LOOP
Modify and re-run the program using PAUSE 20 and note the difference in the
rate that the LED gets brighter and dimmer.
Repeat for PAUSE 5.
You can also use a command called TOGGLE to make this program simpler. TOGGLE
changes the state of a BASIC Stamp I/O pin. If the I/O pin was sending a high signal,
TOGGLE makes it send a low signal. If the I/O pin was sending a low signal, TOGGLE
makes it send a high signal.
Running out of program memory is a problem many people encounter when their BASIC
Stamp projects get large and complicated. Using TOGGLE instead of two FOR…NEXT loops
is just one example of many techniques that can be used to do the same job with half the
code.
LOW 5
DO
Chapter #9: Electronic Building Blocks · Page 267
TOGGLE 5
LOOP
A nominal value means a named value. Parts like resistors and capacitors typically have a
nominal value and a tolerance. Each of the AD5220’s resistive elements has a nominal
value of 78.125 :, with a tolerance of 30% (23.438 :) above or below the nominal value.
Between each of these resistive elements is a switch, called a tap. Each switch is actually
a group of transistors that are switched on or off to let current pass or not pass. Only one
of these switches can be closed at one time. If one of the upper switches is closed (like
pos. 125, 126, or 127), it’s like having the manual potentiometer knob turned most or all
the way clockwise. If pos. 0 or 1 is closed, it’s like having a manual potentiometer turned
most or all the way counterclockwise.
3
A1
Ad5220 78 :
pos. 127
78 :
1 CLK
2 U/D pos. 126
W1 78 :
5 Figure 9-8
7 CS 40 : pos. 125 Inside the AD5220
… …
78 :
pos. 1
78 :
pos. 0 B1
6
Page 268 · What’s a Microcontroller?
Imagine that Pos. 126 is closed. If you want to set the tap to 125, (open pos. 126 and
close pos. 125), set U/D low, then apply a pulse to CLK. If you want to set the tap to Pos
127, set U/D high, and apply 2 pulses. If you want to bring the tap down to 1, set U/D
low, and apply 126 pulses.
This next example program uses the Debug Terminal to ask you which tap setting you
want. Then it decides whether to set the U/D pin high or low, and applies the correct
number of pulses to move the tap from its old setting to the new setting.
With the exception of EEPROM Data, the next example program also has all the sections
you could normally expect to find in an application program:
x Title – comments that include the filename of a program, its description, and the
Stamp and PBASIC directives.
x EEPROM Data – The DATA declarations used by the program.
x I/O Definitions – constant declarations that define I/O pin numbers.
x Constants – constant declarations that define other values used in the program.
x Variables – variable declarations.
x Initialization – a routine that gets the program started on the right foot. In this
next program, the potentiometer’s tap needs to be brought down to zero.
x Main – the routine that handles the primary jobs the program has to do.
x Subroutines – the segments of code that do specific jobs, either for each other, or
in this case, for the main routine.
DO:
LOOP
RETURN
ELSE
DEBUG CR, "New and old settings", CR,
"are the same, try ", CR,
"again...", CR
PAUSE DelayReader ' Give reader time to view
ENDIF ' Message.
RETURN
Pulse_Clk_pin:
' Deliver pulses from old to new values. Keep in mind that Set_Ud_Pin
' adjusted the value of oldTapSetting toward newTapSetting by one.
' This keeps the FOR...NEXT loop from executing one too many times.
Chapter #9: Electronic Building Blocks · Page 271
SUMMARY
This chapter introduced integrated circuits and showed one example of how they can be
used with the BASIC Stamp. A transistor was used as a current valve, and a digital
potentiometer was used to control the amount of current passing through the transistor.
Questions
1. What are the names of the terminals on the transistor you used in this chapter?
2. Which terminal controls the current passing through the transistor?
3. What can you do to increase or decrease the current passing through the
transistor?
4. What is a pin map?
5. What is a reference notch?
Exercises
1. Write a segment of code that makes a BASIC Stamp I/O pin send high/low
signals ten times per second using TOGGLE.
2. Write a segment of code that adjusts the tap in the digital pot to pos. 0 regardless
of what its current setting is.
3. Write a segment of code that sets the tap at pos. 32, then pos. 64, then pos. 96,
then pos. 127. The digital pot should stay at each tap setting for one second.
Projects
1. Add a photoresistor to your project and cause the brightness of the LED to adjust
with the brightness seen by the photoresistor.
2. Connect the AD5220’s CS pin to a BASIC Stamp I/O pin and use it to control
whether or not the chip accepts control signals from the BASIC Stamp. You will
need to disconnect the I/O pin from Vss before connecting it to the BASIC
Stamp’s I/O pin. Keep in mind that a low signal activates the chip, and a high
signal deactivates it.
Page 272 · What’s a Microcontroller?
Further Investigation
The example in this chapter uses a sensor array consisting of two pushbutton circuits, a
potentiometer circuit and a photoresistor circuit. The activities in this chapter will guide
you through building and testing each subsystem individually. After each subsystem is
built and tested, you will then write a program that combines each subsystem into a
working unit. Figure 10-1 shows the circuit schematic for the system you will build, and
the master parts list is below.
Always remember: whenever possible, test each subsystem individually before trying to
make them work together. If you follow this rule, your projects will go much more
smoothly, and your chances of success will be greatly improved. The activities in this
chapter will guide you through the process.
P9
220 :
0.1 µF
Vss
P7
nc
220 :
X
Pot
0.1 µF
10 k:
Figure 10-1
Sensor Array
System Schematic
Vss
Vdd Vdd
P4
220 :
P3
220 :
10 k: 10 k:
Vss Vss
Figure 10-2
First Pushbutton Circuit
Vdd Vin Vss
X3
Vdd
P15
P14
P13
P12
P11
P10
P9
P3 P8
220 : P7
P6
10 k: P5
P4
P3
P2
Vss P1
P0
X2
DO
DEBUG ? IN3
PAUSE 250
LOOP
Figure 10-3
Adding a Second Pushbutton Circuit to the Project
Vdd Vin Vss
X3
Vdd
P15
P14
P13
P4 P12
220 : P11
P10
P9
P8
P7
P6
10 k: P5
P4
P3
P2
Vss P1
P0
X2
Chapter #10: Running the Whole Show · Page 277
Figure 10-4
Adding a Potentiometer Circuit
Vdd Vin Vss
X3
P15
P7 P14
nc P13
220 :
X
P12
Pot P11
0.1 µF P10
10 k:
P9
P8
P7
P6
P5
P4
P3
Vss P2
P1
P0
X2
Verify that the BASIC Stamp gets reliable measurements from the
potentiometer.
Correct any problems you catch before moving on to the next circuit.
DO
HIGH 7
PAUSE 100
RCTIME 7, 1, time
DEBUG HOME, " time = ", DEC5 time
LOOP
Add the photoresistor circuit shown in Figure 10-5 to your project on the
breadboard.
Modify ReadPotWithRcTime.bs2 so the photoresistor is connected to P9.
Correct any problems you catch before moving on to the next activity.
Chapter #10: Running the Whole Show · Page 279
Figure 10-5
Adding the Photoresistor Circuit
Vdd Vin Vss
X3
P15
P9 P14
220 : P13
P12
P11
0.1 µF P10
P9
P8
P7
P6
P5
P4
P3
Vss P2
P1
P0
X2
In the next example program, the ON...GOSUB command uses the value of a variable
named request to direct it to one of four subroutines. If the value of request is 0, the
program executes a GOSUB Read_Pushbutton_1. If the Value of request is 1, the
program executes a GOSUB Read_Pushbutton_2, and so on.
ON request GOSUB Read_Pushbutton_1, Read_Pushbutton_2,
Read_Pot, Read_Photoresistor
You can use the PIN directive to give a name to each I/O pin you are going to use in a
PBASIC program. The BASIC Stamp Editor will then figure out whether you are using
the I/O pin as an input or an output (or both). The PIN directive’s syntax is:
PinName PIN PinNumber
Page 280 · What’s a Microcontroller?
The next example program demonstrates how you can declare and then use a PinName.
For example, the BASIC Stamp Editor assumes that you want to display the input value
of an I/O pin (IN3) if you are using the Pb1Pin PinName in a DEBUG command. This
DEBUG command will display a 1 or 0 depending on whether the pushbutton connected to
P3 is pressed or not pressed. Why? Because the BASIC Stamp Editor knows to
substitute IN3 for Pb1Pin.
Pb1Pin PIN 3
DEBUG CLS, ? Pb1Pin
Here is another example where the BASIC Stamp Editor knows to substitute the value of
9 because the PhotoPin PinName is used in a HIGH command and an RCTIME command.
PhotoPin PIN 9
HIGH PhotoPin
RCTIME PhotoPin, 1, time
Figure 10-6
Using the Debug Terminal to Select from a Menu
Pb1Pin PIN 3
Pb2Pin PIN 4
PotPin PIN 7
PhotoPin PIN 9
DO:
GOSUB Display_Menu
GOSUB Get_Request
ON request GOSUB Read_Pushbutton_1, Read_Pushbutton_2,
Read_Pot, Read_Photoresistor
Page 282 · What’s a Microcontroller?
LOOP
Display_Menu:
Get_Request:
RETURN
Read_Pushbutton_1:
RETURN
Read_Pushbutton_2:
RETURN
Read_Pot:
HIGH PotPin
PAUSE DelayRc
RCTIME PotPin, 1, time
DEBUG CLS, ? time, " "
PAUSE DelayReader
Chapter #10: Running the Whole Show · Page 283
RETURN
Read_Photoresistor:
HIGH PhotoPin
PAUSE DelayRc
RCTIME PhotoPin, 1, time
DEBUG CLS, ? time, " "
PAUSE DelayReader
RETURN
LOOP
Notice that the two subroutines that do the terminal work were commented and the
ON…GOSUB command was placed in a FOR…NEXT loop.
The same as: This DATA directive is the same as Password DATA "p", "a", "s",
"s", "!".
You will need a few variables for storing other values in the program:
index VAR Nib
temp VAR Byte
If you are using a five character password, there is a special kind of variable declaration
(called an array declaration) that you use to declare five variables with the same name.
userEntry VAR Byte(5)
Now you have five byte variables named userEntry: userEntry(0), userEntry(1),
userEntry(2), userEntry(3), and userEntry(4).
The DEBUGIN command has a formatter called STR that automatically loads characters
into an array. For example, you can use:
DEBUGIN STR userEntry \5
If you type five characters in the Debug Terminal’s Transmit Windowpane, the first will
get placed in userEntry(0), the second will get placed in userEntry(1), etc.
There is a PBASIC keyword called EXIT that you can use to break out of a loop. To
check a password, you can use an IF…THEN statement with an EXIT command to cause
the loop to end early if not all the characters are identical. When the loop ends early, it
means that index has not counted all the way up to five, which in turn means the
password was not correct:
FOR index = 0 TO 4
READ Password + index, temp
IF temp <> userEntry(index) THEN EXIT
NEXT
This next example program places the DEBUGIN command, the FOR…NEXT loop, and the
IF…THEN statement inside a DO…LOOP UNTIL statement that keeps executing until the
value of index gets to 5 (indicating the correct password was entered).
Figure 10-7
Entering Password
into the Transmit
Windowpane
DO
DEBUG CR, "Password is correct;", CR, ' Program can move on when
"program can continue..." ' password is correct.
END
Modify the Password DATA directive so that it uses a different five character
password.
By changing five different values in the program, you can also modify it so that
it accepts a four character password instead of a five character password.
GOSUB Check_Password
END
Check_Password:
DO
You will need to tab between each program while copying sections from
ReusablePasswordChecker.bs2 and pasting them into PasswordedSensorTerminal.bs2.
Copy the Password DATA directive (including the commented heading with the
dashed line) from ReusablePasswordChecker.bs2 into
PasswordedSensorTerminal.bs2 just before the I/O Definitions section.
Copy and paste the variable declarations from ReusablePasswordChecker.bs2
into PasswordedSensorTerminal.bs2. These variable declarations are added to
the ones in PasswordedSensorTerminal.bs2, so don’t worry about copying and
pasting the commented Variables heading.
Copy the Initialization section (including the commented heading) from
ReusablePasswordChecker.bs2, and paste it between the Variables section and
the Main Routine in PasswordedSensorTerminal.bs2.
Copy the entire Subroutine section from ReusablePasswordChecker.bs2 and
paste it after the end of the last subroutine in PasswordedSensorTerminal.bs2.
Test PasswordedSensorTerminal.bs2, and see if it works, debug as needed.
Chapter #10: Running the Whole Show · Page 289
SUMMARY
This chapter introduced the technique of individually testing each circuit-subsystem
before integrating it into a larger system. This chapter also introduced the ON…GOSUB
command, which is particularly useful for menu systems. The useful PIN directive was
demonstrated as a way to name your I/O pins and then let the BASIC Stamp Editor figure
out whether to read an input or write to an output. A password program was used to
introduce variable arrays, the EXIT command, and the DEBUGIN command’s STR
formatter. The password program was then integrated into a larger sensor terminal
program to give it more functionality.
Questions
1. When should you test subsystems individually before trying to make them work
together? Why?
2. How many programs did you use in this chapter that were from other chapters?
3. What are the differences between GOSUB and ON…GOSUB?
4. How does the PIN directive differ from the CON and VAR directives?
5. What’s the difference between EXIT and END?
6. How do you declare a variable array?
7. How do you access a particular element in the variable array?
Exercises
1. Explain how to use a FOR…NEXT loop with an ON…GOSUB command to cycle
through a list of subroutines.
2. Explain how to add a menu item to TerminalOperatedSensorArray.bs2 that gives
the operator the option of making a piezospeaker beep.
3. Describe the process you would use (keeping the individual testing rule in mind)
to add a piezospeaker circuit to your project.
4. Modify PasswordChecker.bs2 so that the message "you entered: " appears in the
Debug Terminal along with the text of the password.
Projects
1. Add and test a piezospeaker circuit to the sensor array you developed in this
chapter.
2. Modify TerminalOperatedSensorArray.bs2 so that it has a 5th menu item that
makes the piezospeaker beep at 2 kHz for 1.5 seconds.
Page 290 · What’s a Microcontroller?
Further Investigation
All of the books listed are available for free download from www.parallax.com. The
versions cited below were current at the time of this printing, but please check
www.parallax.com for the latest revisions. We continually strive to improve our texts.
Reference
This book is an essential reference for all Stamps in Class Student Guides. It is packed
with information on the BASIC Stamp series of microcontrollers, the Board of Education
and our other carrier boards, the BASIC Stamp Editor, and our PBASIC programming
language.
“BASIC Stamp Manual”, Users Manual, Version 2.0c, Parallax Inc., 2000
go into modern devices and machinery, working through the activities and projects in the
following Student Guides is highly recommended.
“Advanced Robotics: with the Toddler”, Student Guide, Version 1.2, Parallax
Inc., 2003
“SumoBot”, Student Guide, Version 1.1, Parallax Inc., 2002
“Elements of Digital Logic”, Student Guide, Version 1.0, Parallax Inc., 2003
“StampWorks”, Manual, Version 1.2, Parallax Inc., 2001
“Understanding Signals”, Student Guide, Version 1.0, Parallax Inc., 2003
Appendix A: USB to Serial Adaptor · Page 293
BAFO Downloads: The manual and software for this product can also be downloaded from:
http://www.bafo.com/.
Figure A-1
BAFO BF-810
USB to Serial
Adaptor
This adaptor is
Parallax Stock#
800-00030. It
also comes with a
manual and CD
(not shown).
Page 294 · What’s a Microcontroller?
Appendix B: Equipment and Parts Lists · Page 295
Parts lists are subject to change: Please note that the part numbers and bills of materials
cited in this appendix are subject to change without notice. If you have questions about a
particular part or quantity, please contact the Parallax using the www.parallax.com ĺ
Company ĺ Contact Parallax link.
To complete the exercises in this book, you need to have one of the following Parallax
hardware options:
Option 1:
x Board of Education Full Kit (#28102) - AND-
x What’s a Microcontroller Parts Kit (#28152 with text, #28122 without text)
These two kits are also sold separately. The Board of Education Full Kit (contents listed
below) is the core equipment of the Stamps in Class curriculum, and it can be used with
any of the Stamps in Class texts and kits.
You may purchase the What’s a Microcontroller Parts Kit alone (#28122), or with the
parts and the What’s a Microcontroller? printed text together (#28152). These parts kits
are assembled to support the activities and projects in the current printed version of the
text. The What’s a Microcontroller Parts Kit contents are listed in the table on the
following page.
Page 296 · What’s a Microcontroller?
Option 2:
x BASIC Stamp What’s a Microcontroller Kit (#90005)
This kit features the What’s a Microcontroller Parts & Text, with a HomeWork Board
and accessories that are otherwise sold separately. The BASIC Stamp HomeWork Board
can be used with the What’s a Microcontroller? text in place of the Board of Education
and BASIC Stamp 2 module. The HomeWork Board can also be used in the majority of
the activities in the Stamps in Class curriculum, though occasional circuit modifications
are necessary for certain activities. The BASIC Stamp What’s a Microcontroller Kit
includes the following items:
Figure C-1 shows a close-up of the BASIC Stamp 2. Its major components and their
functions are indicated by labels.
PARALLAX DC SUPPLIES
Parallax carries several power supplies that can be used with the Board of Education Rev
C only. For the servo experiments in this text, the jumper between the X4 and X5 servo
headers should be set to Vdd. The supplies listed in Table D-1 are designed for AC
outlets in the USA, and both have 2.1 mm center-positive barrel plugs that connect to the
Board of Education’s barrel jack.
Table D-1: Power Supplies You Can Get from Parallax, Inc.
Input Output
Parallax Part #
VAC Hz VDC mA
750-00008 120 60 9 300
750-00009 120 60 7.5 1000
Page 304 · What’s a Microcontroller?
GENERIC DC SUPPLIES
For best results with the BASIC Stamp HomeWork Board or any of the Board of
Education Revisions, use a DC supply (also called an AC adaptor) with the following
ratings:
Input
This depends on which country you live in and the amplitude and frequency of the AC
power at the wall outlets. For the USA and Canada, the input should be 120 VAC, 60
Hz.
Output
6 VDC, 800 mA
The mA rating can be higher. A 6 V, 1000 mA supply would be acceptable, for example.
Plug
The Board of Education has both a barrel jack, which can be connected to a barrel plug,
and a 9 V battery connector, which can be connected to a 9 V battery extension. The
HomeWork Board has only the 9 V battery connector.
Barrel Plug
Figure D-1 shows DC supply commonly used with the BASIC Stamp and Board of
Education. It has a 2.1 mm center-positive barrel plug along with the center positive
symbol that is evident on its label.
Appendix D: Batteries and Power Supplies · Page 305
Figure D-1
DC Supply with Barrel Plug
and Center Positive Symbol
9 V Battery Extension
Figure D-2 shows an AC adaptor connected to a 9 V battery extension that can be used
with the BASIC Stamp HomeWork Board. See WARNING discussed next.
Figure D-2
AC Adaptor with 9 V
Battery Extension
Page 306 · What’s a Microcontroller?
TIP TIP
TIP
Figure D-3
Polarity on
Universal
Adaptors
TIP
NOTE: It’s pretty easy to tell when a circuit is drawing more current that the supply can
deliver because the Pwr LED on the Board of Education (or HomeWork Board) flickers
and/or goes dim.
Appendix E: Trouble-Shooting · Page 307
Appendix E: Trouble-Shooting
Here is a list of things to try to quickly fix any difficulties getting the BASIC Stamp
Editor to communicate with the BASIC Stamp:
If you are using a Board of Education Rev C, make sure the power switch is set
to position-1.
Rule out dead batteries and incorrect or malfunctioning power supplies by using
a new 9 V battery.
Make sure the serial cable is firmly connected to both the computer’s COM port
and the DB9 connector on the Board of Education or BASIC Stamp HomeWork
Board.
Make sure that your serial cable is a normal serial cable. DO NOT USE A
NULL MODEM CABLE. Most null modem cables are labeled NULL or Null
Modem; visually inspect the cable for any such labeling. If you find that label,
do not try to use it to program the BASIC Stamp.
Disable any palmtop communication software.
If you are using a BASIC Stamp and Board of Education, also check the following:
Make sure the BASIC Stamp was inserted into the socket right-side-up as shown
in Figure 1-30 on page 18.
If you are using a DC power supply that plugs into the wall, make sure it is
plugged in to both the wall and the Board of Education. Verify that the green
Pwr light on the Board of Education emits light when the DC supply is plugged
in.
Make sure the BASIC Stamp is firmly inserted into the socket. Disconnect
power first, then press down firmly on the module with your thumb. Also
visually inspect the BASIC Stamp to make sure that none of the pins folded
under the module instead of sinking into their sockets on the Board of Education.
If your Identification Window looks similar to Figure E-1, it means that the BASIC
Stamp Editor cannot find your BASIC Stamp on any COM port. If you have this
problem, try the following:
Page 308 · What’s a Microcontroller?
Figure E-1
Identification Window
What’s an Electron? An electron is one of the three fundamental parts of a molecule; the
other two are the proton and the neutron. One or more protons and neutrons stick together
in the center of the molecule in an area called the nucleus. Electrons are very small in
comparison to protons and neutrons, and they orbit around the nucleus. Electrons repel
each other, and electrons and protons attract to each other.
What’s Charge? The tendency for an electron to repel from another electron and attract to
a nearby proton is called negative charge. The tendency for a proton to repel from another
proton and attract an electron is called positive charge. When a molecule has more
electrons than protons, it is said to be negatively charged. If a molecule has fewer electrons
than protons, it is said to be positively charged. If a molecule has the same number of
protons and electrons, it is called neutrally charged.
What’s Voltage? Voltage is like electrical pressure. When a negatively charged molecule is
near a positively charged molecule, the extra electron on the negatively charged molecule
tries to get from the negatively charged molecule to the positively charged molecule.
Batteries keep a compound with negatively charged molecules separated from a compound
with positively charged molecules. Each of these compounds is connected to one of the
battery’s terminals; the positively charged compound is connected to the positive (+)
terminal, and the negative compound is connected to the negative (-) terminal.
The volt is a measurement of electric pressure, and it’s abbreviated with a capital V. You
may already be familiar with the nine volt (9 V) battery used to supply power to the Board of
Education or HomeWork Board. Other common batteries include the 12 V batteries found in
cars and the 1.5 V AA batteries used in calculators, handheld games, and other devices.
What’s Current? Current is a measure of the number of electrons per second passing
through a circuit. Sometimes the molecules bond in a chemical reaction that creates a
compound (that is neutrally charged). Other times, the electron leaves the negatively
charged molecule and joins the positively charged molecule by passing though a circuit like
the one you just built and tested. The letter most commonly used to refer to current in
schematics and books is capital ‘I’.
What’s an amp? An amp is the basic unit of current, and the notation for the amp is the
capital ‘A’. Compared to the circuits you are using with the BASIC Stamp, an amp is a very
large amount of current. It’s a convenient value for describing the amount of current that a
car battery supplies to headlights, the fan that cool a car’s engine, and other high power
devices.
What’s Resistance? Resistance is the element in a circuit that slows down the flow of
electrons (the current) from a battery’s negative terminal to its positive terminal.
The ohm is the basic measurement of resistance. It has already been introduced and it’s
abbreviated with the Greek letter omega (:).
What’s a Conductor? Copper wire has almost no resistance, and it’s called a conductor.
Page 310 · What’s a Microcontroller?
Test Circuit
The resistance value of Ri in Figure F-1 can be changed. Lower resistance allows more
current through the LED, and it glows more brightly. Higher resistance values will cause
the LED to look dim because they do not allow as much current to pass through the
circuit.
If you are using a 9-V battery, you can also compare the brightness of a different voltage
source, Vin. Vin is connected directly to the 9 V battery’s + terminal, and Vss is
connected directly to the battery’s negative terminal. Vdd is called regulated 5 V. That’s
about half the voltage of the 9 V battery.
If you are not using a 9 V battery, stop here and skip to the Calculating the
Current section.
Start with the circuit shown in Figure F-1, but use a 1 k: resistor.
Make a note of how bright the LED is.
Disconnect power
Modify the circuit by disconnecting the resistor lead from Vdd and plugging it
into Vin.
When you plug the power back in, is the LED brighter? How much brighter?
DO NOT try the Vin experiment with a 220 or 470 : resistor, it will supply the LED with
more current than it is rated for.
The rules have to do with how much current an I/O pin is allowed to deliver and how
much current a group of I/O pins is allowed to deliver.
If you know how to calculate how much current your circuit will use, then you can decide
if it’s OK to make your LEDs glow that brightly.
Every electronic component has rules for what it does with voltage, resistance, and
current. For the light emitting diode, the rule you can use is a value called the diode
forward voltage. For the resistor, the rule is called Ohm’s Law. These are facts that you
need to figure out how much current your LED circuit is using. There are also rules for
how current and voltage add up in circuits. These are called Kirchoff’s Voltage and
Current Laws.
Appendix F: More About Electricity · Page 313
Vdd – Vss = 5 V The voltage (electrical pressure) from Vdd to Vss is 5 V. This is called
regulated voltage, and it works about the same as a battery that is exactly 5 V.
Vin – Vss = 9 V If you are using 9 V battery, the voltage from Vin to Vss is 9 V. Be careful.
If you are using a voltage regulator that plugs into the wall, even if it says 9 V, it could go as
high as 18 V.
Ground and/or reference are words you see used to refer to the negative terminal of a
circuit. When it comes to the BASIC Stamp and Board of Education, Vss is considered the
ground reference. It is zero volts, and if you are using a 9 V battery, it is that battery’s
negative terminal. The battery’s positive terminal is 9 V. Vdd is 5 V (above the Vss
reference of 0 V), and it is a special voltage made by a voltage regulator chip to supply the
BASIC Stamp with power.
Ohm’s Law: V = I × R The voltage measured across a resistor’s terminals (V) equals the
current passing through the resistor (I) times the resistor’s resistance (R).
Diode Forward Voltage: When an LED is emitting light, the voltage measured from anode
to cathode will be around 1.6 V. Regardless of whether the current passing through it is a
large or a small value, the voltage will continue to be approximately 1.6 V.
Kirchoff’s Voltage Law Simplified: voltage used equals voltage supplied. If you supply
a circuit with 5 V, the number of volts all the parts use had better add up to 5 V.
Kirchoff’s Current Law Simplified: current in equals current out. The current that
enters an LED circuit from Vdd is the same amount of current that leaves it through Vss.
Also, if you connect three LEDs to the BASIC Stamp, and each LED circuit draws 5 mA, it
means the BASIC Stamp has to supply all the circuits with a total of 15 mA.
Figure F-2 shows how to figure out the voltage across the resistor. The voltage supplied
is on the left; it’s 5 V. The voltages used are on the right. The voltage we don’t know at
the start is VR, the voltage across the resistor. But, we do know that the voltage across
the LED is 1.6 V (the diode forward voltage). We also know that the voltage across the
parts has to add up to 5 V because of Kirchoff’s Voltage Law. The difference between 5
V and 1.6 V is 3.4 V, so that must be the voltage across the resistor VR.
Page 314 · What’s a Microcontroller?
Vdd
+
+
VR = ? V Figure F-2
VR 1.6V 5V
5V - Voltage Across
VR 5V 1.6V the Circuit,
+ Resistor, and
VR 3.4V
1.6 V LED
-
-
Vss
Kilo is metric for 1000. The metric way of saying 1000 is kilo, and it’s abbreviated with the
lower-case k. Instead of writing 1000 :, you can write 1 k:. Either way, it’s pronounced
one-kilo-ohm. Likewise, 2000 : is written 2 k:.
Milli is metric for 1/1000, and it is abbreviated with a lower-case m. If the BASIC Stamp
supplies an LED circuit with 3.4 thousandths of an amp, that’s 3.4 milliamps, or 3.4 mA.
What’s a mA? Pronounced milliamp, it’s the notation for one-one-thousandth-of-an-amp.
The ‘m’ in mA is the metric notation for milli, which stands for 1/1000. The ‘A’ in mA stands
for amps. Put the two together, and you have milliamps, and it’s very useful for describing
the amount of current the BASIC Stamp and the circuits connected to it draw.
How much current is 7.23 mA? It’s the amount of current the LED shown on the right side
of Figure F-3 conducts. You can replace the 470 : resistor with a 220 : resistor, and the
circuit will conduct 15.5 mA, and the LED will glow more brightly. If you use a 1000 :
resistor, the circuit will conduct 3.4 mA, and the LED will glow less brightly. A 2000 :
resistor will cause the LED to glow less brightly still, and the current will be 1.7 mA.
Figure F-3 shows an example of how to calculate the current the circuit uses if the
resistor is 470 :. Start with Ohm’s Law. You know the answers to V (3.4 V) and R
(470 :). Now, all you have to do is solve for I (the current).
Appendix F: More About Electricity · Page 315
V IuR
3.4V I u 470 :
3.4V
I
+ 470 :
Figure F-3
3.4 V I X 470 : I 0.00723V Current through
: the Resistor
-
I 0.00723 A
7.23
I A
1000
I 7.23 mA
Yes, it’s true - 1 A = 1 V/: (One amp is one volt per ohm).
Let’s say you turned two LEDs on at the same time. That means that inside the BASIC
Stamp, it is supplying the circuits as shown in Figure F-4. Have we exceeded the 20 mA
limit? Let’s find out. Remember that the simplified version of Kirchoff’s Current Law
says that the total current drawn from the supply equals the current supplied to all the
circuits. That means that I in Figure F-4 has to equal the total of the two currents being
drawn. Simply add the two current draws, and you’ll get an answer of 14.5 mA. You are
still under the 20 mA limit, so your circuit is a safe design.
Vdd
I=?
Figure F-4
I I1 I 2 ...I i
Total Current
7.23 mA 470 : 7.23 mA 470 :
I 7.23 mA 7.23 mA Supplied to
I 14.5 mA Two LED
Circuits
LED LED
Vss Vss
Page 316 · What’s a Microcontroller?
The text before the first colon is what the cell phone displays as the name of the song. In
this case, the ringtone is named:
TakeMeOutToTheBallGame:
Between the first and second colon, the default settings for the song are entered using d,
o, and b. Here is what they mean:
d – duration
o – octave
b – beats per minute or tempo.
The notes in the melody are entered after the second colon, and they are separated by
commas. If just the note letter is used, that note will be played for the default duration in
the default octave. For example, the second note in TakeMeOutToTheBallGame is:
,c,
Since it has no other information, it will be played for the default quarter note duration
(d=4), in the seventh octave (o=7).
A note could have up to five characters between the commas; here is what each character
specifies:
,duration note sharp dot octave,
For example:
,2g#.6,
Page 318 · What’s a Microcontroller?
means play the half note G-sharp for 1 ½ the duration of a half note, and play it in the
sixth octave.
The character:
,p,
stands for pause, and it is used for rests. With no extra information, the p plays for the
default quarter-note duration. You could also play a half note’s worth of rest by using:
,2p,
In this case the rest would last for a half note plus a quarter note’s duration.
Index · Page 319
Index
-%-
Identification Window, 20
%, 173 Identify, 308
-*- Memory Map, 257
*, 94 Software, 5
**, 239 Trouble-Shooting, 307
*/, 95, 239
BASIC Stamp HomeWork Board, 14
-3- BASIC Stamp HomeWork Board
3-position switch, 17 Components, 301
-7- Battery, 14, 45
7-Segment Display, 161–66 Beat, 222
Bi-Color LED, 60
-A- Binary Numbers, 21, 77, 173
Active-High, 79 Bit, 54, 171, 243
Active-Low, 79 Board of Education, 13
AD5220 Digital Potentiometer Components, 300
Pin Map, 262 Full Kit, 295
Pin Names and Functions, 262 Revision label, 102
Algorithm, 96 Servo Header, 104
Amp, 309
Anode, 40 Board of Education Rev B
Array, 284 Components, 302
ASCII Codes, 226
Boe-Bot, 2
-B- Breadboard. See Prototyping Area
Byte, 54, 226, 243
Base, 259
BASIC Stamp -C-
BASIC Stamp 2 Module, 1 Cadmium Sulfide, 185
Components, 299 Capacitor, 139–41, 145
HomeWork Board, 297 Ceramic, 146
Polar – identifying terminals, 139
BASIC Stamp Editor
Page 320 · What’s a Microcontroller