CHAPTER 15

THE BASIC STAMP 2
MICROCONTROLLER
If you are familiar with the second edition of this book, you know that the example robot control circuits and programs were written for four different platforms: the PC’s parallel port, the Parallax BASIC Stamp, the BasicX microcontroller (MCU), and the OOPic microcontroller. Each of these different platforms provides unique capabilities, but the end result was a book with a bit of a mishmash of different applications, which required the reader to understand each of the different hardware and software development platforms to know what the application was doing and how to convert (or port) it to the one that would be used with the robot. To simplify the book and your work in understanding how each application is to be implemented, it was decided to cut down the number of robot controllers described in the book to one.
Choosing a single example microcontroller with software for the book was not an easy task because there are literally hundreds of different microcontrollers with an equal number of software development tools that go with them. In the end, the decision was made to go with the Parallax BASIC Stamp 2 (abbreviated BS2), one of the devices that was already described in the second edition. The BS2 has the following features, which make it a good choice for new robot developers:
As you gain experience and sophistication, the downsides of the BS2 compared to other MCU solutions will become apparent. Many of these issues are a result of trade-offs to provide pin-specific functions or downloadability (in a chip that didn’t have this feature when the BS2 was first designed). For example, once you have bought one BS2, the price of subsequent units does not go down because you already have the programmer and development software. As noted, the programmer interface is built into each BS2 rather than buying a single programmer and using that for multiple chips, as is done in most other MCUs. The +5 V regulator is somewhat fragile and cannot be used to power much more than just some LEDs and other basic interfaces. When the BS2 was designed (in the late 1990s), all PCs had RS-232 interfaces, which made sense at the time; now, with RS-232 being phased out of many systems, you will have to buy an USB to RS-232 converter. Finally, the execution speed is about 4000 statements per second, fast enough for most robot requirements but not fast enough for sophisticated interfaces.
Despite these issues, the BS2 is an excellent first MCU to work with and remains a favorite of many robot designers, both beginner and expert. The MCU itself is very reliable (especially after following a few rules that are outlined in this chapter); the software development tools are rock-solid stable (something you will appreciate more as you become more familiar with different systems); and Parallax provides an excellent selection of data sheets and application notes along with a full line of interfacing and support products for you to choose from.
When you see most projects that have a BASIC Stamp in them, they use the standard 24 pin, 0.600-in wide DIP package shown in Fig. 5-1 This is only one of several packages and optional features that are available for the microcontroller. While the 24 pin package is the most popular and the one that you are most likely to use, there are about a dozen different ways that you could use BASIC Stamp packages in your robot. Some of these packages also make the integration of the MCU into the robot a lot easier than using the 24 pin package.
images
To start off, the Stamps are all designed with a similar architecture; a general-purpose microcontroller is connected to the programming interface to provide a download interface from a PC to the electrically erasable programmable read-only memory (EEPROM) program memory. During program execution, this microcontroller reads the EEPROM, interprets the program instructions, and carries them out using its built-in I/O pins. The I/O pins can be used for a variety of different purposes over and above simple digital input and out-put. The microcontroller is usually referred to as the interpreter chip. Along with the microcontroller, EEPROM, and serial programming interface, the Stamp has a power supply that will convert +5 to +15 V DC to 5 V for use by the microcontroller as well as some devices connected to the Stamp, an oscillator for the microcontroller along with a reset circuit. It should be obvious that while the Stamps are referred to as chips (primarily because they plug into a chip socket) they are actually complex modules that integrate a number of different components into a single microcontroller function.
There are three Stamp product families that you should be aware of. The first is the venerable BASIC Stamp 1 (BS1), which first came out in 1992. This microcontroller is built in either a very small single in-line package (SIP) (1.4 in long and 0.6 in high) using SMT parts or on a larger PCB (2.5 in by 1.5 in) that includes a small prototyping area. The BS1 has eight I/O pins and runs at a rate of about 2000 instructions per second. The EEPROM, which is used to store the program, will store about 80 instructions. There are a total of 14 variable memory bytes available. The BS1’s parallel port programming differs from the other BASIC Stamps and is one of the features that makes it difficult to work with; Windows/ 2000 and Windows/XP, which are the most commonly used PC operating systems, do not allow programs direct access to the Parallel port. Parallax sells (and has published the schematic so that you can build it yourself) a serial to parallel BS1 programming interface so that the BS1 can be used with the latest versions of Windows (using the latest BASIC Stamp interfacing software).
TABLE 15-1   The Features of the Different BS2s
table
 
In Table 15-1   the BASIC Stamp’s speed is measured in instructions per second; the different BS2s execute 4000 (4k) to 19,000 instructions per second. This is a surprisingly accurate specification for simple operations, and the reciprocal of the speed specification can be used to roughly calculate the operation time of a block of code.
RAM and EEPROM are specified in bytes, and while the EEPROM seems reasonable, the 26 bytes of RAM (used for variables) probably seems to be unusable. Look through the example applications presented in this book and you will probably be surprised to see that very sophisticated applications can be created for the BS2, despite the apparently limited variable memory available to it.
As a rule of thumb, remember that every 2k of EEPROM will store 500 Stamp BASIC statements.
Along with a set number of general-purpose I/O pins, there are two RS-232 serial interface I/O pins available for application use and communicating with another computer. The RS-232 interface consists of a voltage stealing circuit, so a standard -15 to -3 V and +3 to +15 V RS-232 can be used safely. The RS-232 serial port pins double as programming interface and debug communications pins. All I/O pins, except for the two serial interface pins are bi-directional and perform a variety of different functions that are described later in this chapter.
Finally, the amount of current the I/O pins can source (provide to a device) or sink (take away from a device) is measured in milliamps. With the fairly low currents output from the different stamps, it should be noted that they can only control a logic gate, transistor, or LED or two. They do not have sufficient power to drive motors or other magnetic devices.
All the BASIC Stamps have a built-in power supply, but as I will discuss later in this chapter, it should be bypassed for most applications and instead an external regulated power supply should be used. The reason for this recommendation is due to the low current sourcing capability of the power supply on the BS2—if an excessive amount of current is drawn the power supply can be burned out.
The Javelin Stamp executes Java code rather than the Stamp BASIC of the other two types of Stamps. It executes approximately 8.5k instructions per second and has 32k bytes of variable space as well as 32k of EEPROM program memory. The Javelin is generally plug compatible with the BS2, but there will be issues with timing the code to match the application timing of the BS2s.
With all these different Stamp options to choose from, which one is right for you?
For most applications and if you are starting out, the simplest BASIC Stamp 2, the BS2- IC will probably be the best. This part, while seemingly less than the other versions of the BS2, will be fast enough and have enough EEPROM memory for most applications and it costs as much as 40% less than the other BS2s. The application code written for the BS2- IC can be used with only very minor changes (specifically in the areas of timing) in the other BS2 part numbers, so any investment in software will not be wasted if high-performance BS2s are required later.
Starting at the low end of any device family is always a good idea. With the BASIC Stamp 2, there are 20 to 30 different permutations and combinations or BS2 part number, packaging options, and carrier board options. If you consider the literally thousands of different microcontrollers available in the market that could be used in a robot, the number of options that you have would certainly be greater than 10,000. As you learn more about electronics, programming, and microcontrollers, you will begin to develop preferences for different technical features in the chips you work with; but for now, start with a simple device that is extremely popular (which means there are a number of applications and books that you can reference), can be interfaced to and programmed easily, and is supported by an excellent company with a good variety of data sheets, products, and services you can rely on. When these factors were taken into consideration, the BS2 seemed to be the correct single choice for demonstrating in this book how a microcontroller worked rather than trying to use a variety of different devices for the job.
When the BASIC Stamp was first designed, low-cost electrically reprogrammable microcontrollers did not exist; this led to the decision to create one by adding a serial EEPROM memory along with a preprogrammed MCU, which resulted in the ability to download and execute applications written on a PC. Fig. 15-2 expands on Fig. 15-1 and shows the circuitry connected to each of the BS2’s pins. Instead of building a robot control circuit out of numerous inverters, AND gates, flip-flops, and other hardware, you can use just the BS2 module to provide the same functionality and do everything in software.
images
Because the Stamp accepts input from the outside world, you can write programs that interact with that input. For instance, it’s easy to activate an output line—say, one connected to a motor—when some other input (like a switch) changes logic states. You could use this scheme, for instance, to program your robot to reverse its motors if a bumper switch is activated. Since this is done under program control and not as hardwired circuitry, it’s quite simple to change and enhance your robot as you experiment with it.
In operation, your PBASIC program is written on a PC, then downloaded—via a serial connection—to the BASIC Stamp, where it is stored in EEPROM, as shown in Fig. 15-3. The program in the EEPROM is in the form of tokens, special instructions that are read, one at a time, by the PBasic interpreter stored in the BASIC Stamp’s PROM memory. During program execution, temporary data is kept in RAM. Note that the EEPROM memory of the BASIC Stamp is nonvolatile—remove the power and its contents remain. The same is not true of the RAM. Remove the power from the BASIC Stamp and any data stored in the RAM is gone. Also note that the PBASIC interpreter, which is stored in the programmable read-only memory (PROM) of the interpreter microcontroller, cannot be changed.
images
The BASIC Stamp 2 is available directly from Parallax, its manufacturer, or from a variety of dealers the world over. In addition to the BS1, BS2, and Javelin Stamp and the variations listed previously, you’ll find that there are several assembled development boards that can be used as the complete circuitry for your robots.
images
Parallax has designed a number of robots that use the BASIC Stamp 2 as the central processor and use the developer products listed (like the Board of Education PCBs in the case of the Boe-Bot) as carriers. These robots are well designed, consist of high-quality parts, and have excellent documentation. As the creators of PBASIC and the BS2, Parallax has provided additional features to its robots, such as the Gui-Bot software, which provides a graphical programming environment for the BS2 built into the Boe-Bot.
A number of other manufacturers have designed development boards and products around the BS2. The Tab Electronics Sumo-Bot kit from McGraw-Hill is a differentially driven, tracked robot that has a serially programmed BS2 built into it for user programmability.
At the heart of the BASIC Stamp series of microcontrollers is the PBASIC programming language. PBASIC has undergone a number of changes over the years and has developed from a very rudimentary language to the current incarnation (2.5 at time of writing), which includes structured programming statements and methods of accessing pins that will make applications easier to read and understand.
images
If you do not use Windows, there are Linux and Macintosh (OS 9 and later) versions of the PBASIC software written by Stamp enthusiasts that can be downloaded off the Internet. Along with these interfaces, Parallax has made the tokenizer (which is called the compiler in this book) for PBASIC available for Windows, Linux, and Mac OS/9+. To find out more about this software, check the Parallax web site for pointers to locations for download.
Like any language, PBASIC is composed of a series of statements strung together in a logical syntax. A statement is compiled into a series of instructions that the BS2’s interpreter chip carries out or executes. For example, one statement may tell the chip to fetch a value on one of its I/O pins, while another may tell it to wait a certain period of time.
The majority of PBASIC statements can be categorized into four broadly defined groups: variable and pin or port definitions, assignment statements with arithmetic expressions, decision structures, and built-in functions. A PBASIC program will contain elements taken from each group.
The following sections provide an introduction to the PBASIC language with just enough information for you to become dangerous, as the saying goes. For a complete PBASIC language definition, you should go to the Parallax web site and download the PBASIC Language Specification, study it, and experiment with the different features and functions available to you for the BASIC Stamp MCU that you are working with.
PBASIC uses labeled variables as the methodology to store data as well as allow you to read and change the I/O pins of the microcontroller. The variables themselves can be of several different sizes; since there are only 26 bytes of RAM available for use as variables you should always strive to choose the smallest variable size that will accommodate the data you wish to store. The I/O pins can be accessed in a variety of different ways, as will be discussed in this section.
  PBASIC provides the following four variable types:
  • Bit—1 bit (0 or 1)
  • Nibble—4 bits (0 to 15)
  • Byte—1 byte (0 to 255)
  • Word—2 bytes (0 to 65,535)
Variables must be declared in a PBASIC program before they can be used. This is done using the var statement, as in
VarName var VarType
where VarName is the name (or symbol) of the variable, and VarType is one of the variable types just listed. VarName must start with an alphabetic (a through z) or underscore (_) character and the remaining characters can be alphabetic, underscore, or numeric (0 through 9). Here are some examples:
Red   var bit
Blue var byte
After reading these statements, the PBASIC compiler will make Red a bit variable and Blue a byte. It should be noted that the PBASIC compiler is pretty good at compressing variables—up to eight bits in a byte, or two nibbles in a byte.
In these examples and in the example code throughout the book, the capitalization of the variables is fairly carefully thought out. This is due to the authors’ experience with other high-level languages that do track capitalization whereas PBASIC ignores variable name and other label capitalization. The Stamp Editor will capitalize reserved words to make them stand out visually, but if you were to key in a program in a standard text editor, the capitalization specified in the text file would be unchanged and ignored by the PBASIC compiler. The following declaration statements produce the same result as the previous ones:
Red   Var Bit
BLUE VAR BYTE
Single dimensional arrays can be specified by simply stating the desired number of elements for the array as part of the type definition:
images
The text after the single quote (') is known as a comment and is specifically for the use of the human reading the code. Code following the single quote is ignored by the compiler.
Finally, variables can be redefined or smaller parts of variables used to extract specific data information. For example, to look at bit 2 of a returned data variable:
images
Once declared, variables can be used throughout a program. The most rudimentary use for variables is part of the assignment statement, which is discussed in the next section. In later sections, comparisons to different values and use in built-in functions is discussed.
Variables store values that are expected to change as the program runs. PBASIC also supports constants, which are used as a convenience for the programmer. Constants are declared much as variables are, using the con statement:
MyConstant con 5
Any time MyConstant is encountered in the PBASIC program, the string MyConstant is replaced with the value 5.
The BASIC Stamp treats its 16 I/O pins like additional memory that can be accessed like variables or using special functions. There are actually three different ways of accessing I/O pins, which can be confusing for new programmers, especially when the tri-state driver functions are included into the mix.
Each pin has three bits associated with it. The IN bit returns the data value at the output pin. OUT is written to set the output state of the pin (if it is in output mode) and can also be read back. The DIR bit is used to specify whether the pin is in input mode (value 0 and cannot output a logic signal) or output mode (value 1 and can drive a logic signal from the pin).
These three bits are generally thought of as part of three 16-bit variables. INS is the 16- bit variable for each of the 16 IN bits, OUTS is the 16-bit variable for each of the 16 OUT bits, and DIRS is the 16-bit variable for each of the 16 DIR bits. The bits can be accessed as 16 bit (suffix S), 8 bit (suffix L or H), 4 bit (suffix A to D), or 1 bit (suffix 0 to 15). The suffix describes the number of bits and which ones. For example, DIRL will access the lower 8 bits of the DIRS variable. To help understand how these variables operate, look at the I/O Port Simulator at the end of the example applications in this chapter.
Another way to access the I/O pins is to avoid the IN, OUT, and DIR variables all together and use the built-in pin I/O functions of PBASIC, which take a numeric value or a pin variable name (described in the following):
images
The problem with this method is that it does not allow for easy reading of the input pins without using the built-in variables previously specified, which can get confusing when you are new to programming. The pin declaration
MyPinName pin 4
will create a combination of a variable and constant so that you can access a pin value like a variable or specify its operating mode using one of the five built-in functions previously listed. For example, to create an input pin and poll (read) its value, you could use the code:
images
The most fundamental operation that the BS2 (or any computer system for that matter) provides is data movement and manipulation. Without this ability, new outputs cannot be derived from the inputs, and execution changes due to changes in the environment are not possible. The assignment statements and arithmetic expressions used in the BS2 are very similar to their counterparts in other programming languages.
The assignment statement simply evaluates an arithmetic expression and stores the result in a variable. The format of the assignment statement is:
VarName = expression
While the VarName = part of the assignment statement looks straightforward, the expression part probably seems ominous. There’s no need to worry; the term expression simply means some number of characters, representing a series of arithmetic operations that evaluate to a numeric value. The assignment statement’s expression can be as simple as a constant value like
images
or it can be another variable
images
Expressions can also be arithmetic operators changing a value in some way. For example, if you wanted to save the value of A multiplied by four in B, you could use the assignment statement and expression combination:
images
Table 15-2 lists the different expression operators built into PBASIC that can be used with assignment statements. Note that some of them operate with one parameter while others work with two. Only the minus sign (-) can be used with either one parameter or two; when it is before (to the left of) the parameter, it returns the two’s complement negative value of the parameter, and when it is between two parameters it subtracts the second from the first.
 
Multiple operations can be built into an expression, but there is a facet of PBASIC that is different from other programming languages. Normally in a programming language, there is an order of operations that specifies how mathematical operations in an expression execute. In PBASIC, there is no order of operations. Everything executes from left to right unless there are parentheses to help explain the desired order of operations.
For example, if you were to convert a temperature in Fahrenheit to Celsius, you would want to use the arithmetic expression:
DFahrenheit = 9 / 5 * DCelsius   +   32
This statement would evaluate 9 divided by 5 (1), and multiply it by DCelsius and then add 32 before saving the result in DFahrenheit. The division took place first because it is the left-most operator. Dividing constant values can be tricky because numeric values in PBASIC (and other microcontroller programming language values) are integers (with no decimal points) only. Before doing any division, remember to always do the multiplication first.
To force the PBASIC compiler to put your arithmetic operators in the desired order, put parentheses around the higher priority (and first executing) operators and their parameters. Using parameters to fix the degree conversion assignment statement becomes:
images
When you have more than one operator in an assignment statement, it is usually referred to as a complex assignment statement and it is a good idea to use parentheses to ensure the expression is evaluated in the order you want.
Normally, software flows from one statement to the next with each statement performing calculations or inputting or outputting data that are required to meet the application’s specifications. In the first computer systems, the programs performed basic calculations and stopped when the answer had been calculated. In robot systems, this is not possible because the robots run continuously; for the programs to execute from line to next line continuously the programs would have to be literally infinitely long. To avoid the chore of writing infinitely long programs, computer scientists came up with the concept of looping a section of code along with being able to change where the program executes algorithmically using decision structures. Decision structures is a ten-dollar phrase that describes the programming statements that change the flow of the program’s execution based on different inputs and variables. Before you can successfully develop application software programs, you have to understand how a program flows and changes operation using decision structures.
Essentially all robot programs are based on the program template:
images
All of the statements in this example program structure can be implemented using the assignment statement except for the Loop Start and Loop End. The Loop End statement causes execution flow of the program to jump back to the start of the loop code, which is indicated by Loop Start. In PBASIC, Loop Start and Loop End are implemented using the DO and LOOP statements, changing the robot program structure to:
images
Using the DO/LOOP statements, the steps within them are continuously repeated, eliminating the need to write an infinitely long program. Additional loops can be put inside the main loop. There will be cases, however, in which you want the looping to take place for a certain length of time or while some condition is true.
The DO/LOOP (pronounced “do loop”) statements can execute conditionally when WHILE or UNTIL conditions are attached to them. After the WHILE or UNTIL words, a comparison expression is used to indicate when the looping should stop. In Table 15-3, the different types of DO/LOOPs are listed with the WHILE and UNTIL words in place, and Table 15-4 lists the six comparison expressions that can be used with WHILE and UNTIL. Note that the WHILE or UNTIL and comparison expressions can be placed either at the start of the loop (testing before going in the first time) or after working through the loop statements at least once.
TABLE 15-3   Different Forms of the PBASIC DO/LOOP
table
 
The comparison expression is in the format
 
VarName|Constant operator VarName|Constant
 
where VarName|Constant is a variable or constant and operator is the equals, less than, or greater to sign, in one of the six combinations shown in Fig. 15-4. The complement value is the opposite and lets you use the complement word (UNTIL is the complement of WHILE and vice versa). When WHILE or UNTIL is used with the DO/LOOP, loops execute a set number of times, as in the following example:
images
Note that the code statements inside the DO/LOOP are indented a number of spaces. This optional indentation makes it easier for people to see which code is part of a loop and what is outside it. This convention is used by most programmers and is one that you should follow to make it easier for both yourself and others to read the source code.
In this example code, the code inside the loop executes seven times before execution flows out of the loop and on to the rest of the program. The DO WHILE/LOOP statement can be used for this purpose, but it is more traditional to use the FOR/NEXT statements:
images
The FOR statement initializes a variable with an initial value and then executes until the variable is equal to the final (end) value with the variable being incremented during each loop. If no StepValue is specified, then the incrementing value is one. Using the FOR/NEXT, the seven times loop code shown previously could be reduced to:
images
While the program space gains seem to be marginal over the DO/LOOP, the major advantage of using the FOR/NEXT in this case is how obvious it is to somebody reading the code. Rather than decoding the DO/LOOP statements, the FOR/NEXT is known to be a counting loop.
Before going on, it should be pointed out that the comparison expressions of the DO/LOOP statements can be expanded beyond the simple examples shown so far. First, the comparison values can have arithmetic operators, causing them to calculate values in the DO/LOOP statement as shown below:
images
Like the complex arithmetic expressions described in the previous section, remember that the evaluation of the expressions takes place left to right with priority given to values and operators in parentheses. When you are starting out, it is probably a good idea to avoid performing calculations in your comparison expressions until you are very comfortable with programming.
The second enhancement to the comparison operators is the ability to AND as well as OR the results of multiple comparison operators together:
images
To make reading the program easier, remember to place each comparison expression inside parentheses (and this is actually a pretty good idea anyway).
Along with looping a program or sections of the program for a set number of times, it is also possible to execute blocks of code conditionally. The traditional way of doing this is to use the IF/ELSE/ENDIF statement which evaluates a conditional expression and if the result is true executes specific code. As shown in the following example code, the condition expression of the IF/ELSE/ENDIF statements is exactly the same as the one used with the DO/LOOP:
images
The code after the ELSE statement executes if the comparison expression evaluates to false. Another way of saying this (refer back to Fig. 15-4), is that the ELSE code executes if the complement comparison expression is true. The ELSE code is optional and no part of it will execute if the comparison is true.
Along with the IF/ELSE/ENDIF statements, if there are multiple constant values for a variable that each result in a different execution path, then the SELECT/CASE/SELECTEND statements can be used to specify blocks of code that execute when the variable is compared to any of these values.
images
The SELECT/CASE/ENDSELECT statements could be modeled using IF/ELSE/ENDIF statements arranged as:
images
Note that when the multiple IF/ELSE/ENDIF statements are used together, each line is indented to indicate what previous statement it executes under.
The DO WHILE/LOOP, DO UNTIL/LOOP, DO /LOOP WHILE, DO /LOOP UNTIL, IF/ELSE/ENDIF, and SELECT/CASE/ENDSELECT statements and the code associated with them are known as decision structures because they are well-defined blocks of code that execute based on the result of a test (or decision). They also go under other names such as flow control or conditional execution statements. Regardless of their name, they are common to most programming languages that you will be working with.
If you are already familiar with PBASIC or are referencing other books about BS2, you will probably see that a whole class of decision structures, the IF/THEN and BRANCH, statements is not mentioned. Along with this, if you look on the Internet for sample applications, you probably won’t see the decision structures listed here at all in the code.
With the introduction of PBASIC 2.5, Parallax introduced these decision structures to allow the application developer to write code using structured programming methodologies. Structured programming eschews the use of GOTO statements as they make a program difficult to read and certain operations, like rewriting the previous IF/ELSE/ENDIF example code.
images
difficult to implement correctly. (The character strings ending in a colon (:) are labels and indicate specific points in the code execution should jump to.) It is considered good programming form to only use structured programming statements, such as the ones presented in this section, and avoid the use of GOTOs or statements that execute GOTOs all together.
Finally, it was implied at the start of the section that all programs should use the program template provided previously as a basis for application programs, which required the use of a DO/LOOP implemented as an infinite loop. There are cases where you will want to execute a simple program that executes a number of statements and stops. This type of program is good for experimenting with the BS2 and learning about different PBASIC statements and functions.
When implementing this type of program, always remember to place an END statement at the bottom of the code. The END statement stops the BS2’s interpreter and leaves the I/O pins in their current state until power or the reset pin is cycled or a new program is loaded into it. Depending on the function of the example program, either a DO/LOOP is used or an END statement.
The PBASIC language supports several dozen built-in functions that are used to control some activity of the chip, including sounding tones through an I/O pin or waiting for a change of state on an input. The following functions are among the most useful for robotics. You’ll want to study these statements more fully in the BASIC Stamp manual, and more information regarding many of them are discussed elsewhere in this book.
images
These statements are useful when communicating with a variety of external hardware, including serial-to-parallel shift registers and serial analog-to-digital converters.
Before going on to interfacing the BS2 (or any other microcontroller) into robots or a final application, you should spend some time learning how to program, create electrical interfaces, and debug applications. In the following sections, some simple applications are presented along with basic wiring information for the BS2 that will come in handy when you are creating your own applications.
A quick Internet search will also yield many different sites with information on robots and microcontrollers. For instance, as this edition of the book was written, a Google search of BS2 and Robots yielded over 10,000 sites. Even if only 1 out of 10 sites had a BS2 application on it, there are over 1000 projects that you can choose from or use as a reference for your robot. Along with links to web pages, you should also consider joining one of the Yahoo! list servers (some listed in the appendices) to share your ideas and ask questions of others.
Please do not consider this book as the ultimate resource on the BS2 and how it is used in robot applications. Go through the appendices for additional introductory how-to reference books on the BS2 and how microcontrollers can be used with robots. The more time spent learning about a specific microcontroller, building your own circuits, and trying different programs as well as seeing a variety of different people’s perspectives will minimize the problems that you will have later when you are wiring up and programming your robot.
At the start of this chapter, it was noted that the BS2 could be programmed cheaply and easily. Unlike other microcontrollers, you can create a breadboard-based development circuit like the one shown in Fig. 15-7 for about $10 (if you use new parts). The circuit consists of a serial interface to your PC along with a small breadboard, a box of precut wires, a breadboard-mountable DPST switch (an EG-1903 is used in Fig. 15-7), and a three AA battery clip attached to the breadboard’s backside two-sided tape. The entire package can be built in about 20 minutes and once the BASIC Stamp Editor software has been downloaded into your PC you are ready to go!
images
The biggest piece of work is soldering five wires and a jumper to a nine-pin female D-shell connector to make the serial communications/programmer interface as shown in Fig. 15-8) (a photograph of an assembled prototype is shown in Fig. 15-9)). The BS2 is programmed via RS-232. If your PC does not have a serial port, you can buy a USB to RS-232 adapter. The parts needed to put the interface connector together are listed in Table 15-5. You might be tempted to put the two 0.1 μF capacitors onto the breadboard, but you will find that by spending a few extra minutes soldering them to the nine-pin female D-shell, the effort of having to come up with the most efficient breadboard wiring will be avoided each time the BS2 is used in an application. Also note that the four wires (each a different color to aid in keeping track of them) were cut to the same length with a images in (1 cm) or so of bared copper and bent in the same direction to allow them to be pressed into the breadboard.
images
 
images
 
Connector
Female nine-pin D-shell connector
Capacitors
0.1 μF capacitors (any type)
Misc.
24 gauge wire, different colors

When you’ve assembled the serial communications/programming interface, cut a strip of the two-sided tape off the back of a small breadboard and stick on a three or four AA battery clip. For the BS2 to work properly, 4.5 to 6 V must be applied to it. If you are going to use alkaline cells (which produce 1.5 to 1.8 V each), only three batteries are required. If you are going to use NiMH rechargeable batteries (which produce 1.2 V), then four batteries will be required.
You might also want to put a power switch in line with the positive voltage from the battery pack. The positive and negative voltage should be connected to the common strips on the breadboard and connected to VDD (pin 21) and VSS (pin 23), respectively. VIN and the on-board voltage regulator is bypassed as is the _RES (Reset) pin. The BS2 will power up any time power is applied to it.
With the hardware together, you can download the BASIC Software Editor (from www.parallax.com “Downloads”) and install it on your PC. Along with Windows software, there are also Linux and Mac editors available. The editor should install like any other application and once you have connected the serial port to a straight-through nine-pin male to nine-pin female cable, you are ready to try out your first application!
The typical first application of any computer system is the Hello World, which follows. This program will simply print out the welcome phrase to indicate that it is up and running. Key in the program to the BASIC Stamp Editor, save it on your PC’s desktop, and then either click on the right-pointing triangle on the toolbar or press Ctrl-R. This will compile, download, and then run the application.
images
If the program was keyed in correctly and the wiring is correct, a terminal Window should appear with the message “Hello World.” If there is an error message indicating there is a problem with the program, check what you’ve keyed in to make sure the program has been entered correctly. If the PC cannot find a BS2 connected to it, check the wiring of the nine-pin D-shell connector and that at least 4.5 (but not more than 6.0) V is going into the BS2’s pin 21 and 23. Additional debugging information can be found in the BASIC Stamp Syntax and Reference manual downloadable from the Parallax web site.
With the software loaded on your PC and a simple programming/communications interface built and tested for your BS2, you can now start experimenting with the input/output capabilities of the microcontroller. The most fundamental output device that is used with a microcontroller is the light-emitting diode (LED) and with it you can learn a lot about programming and how the BS2 works.
To demonstrate LED interfacing in this and the next section, you should wire the circuit shown in Fig. 15-10, consisting of the BS2, the programming/communications interface, and eight LEDs, wired to the low eight bits of the BS2’s I/O port. The parts required for this circuit are listed in Table 15-6. To simplify the wiring in the prototype, eight 5 × 2 mm rectangular LEDs were used instead of square LEDs Fig. 15-11
images
 
images
 
BS2
Parallax BASIC Stamp 2
LEDs
5 × 2 mm Red LEDs
Programmer
BS2 Programmer/Communications Interface
Misc.
Breadboard, 3x AA Alkaline Battery Clip, Switch Breadboard Wires,
Power
 
The first task you might want to perform is to flash a single LED (we’ll get to the other LEDs later in this section) by performing a delay, turning the LED on, waiting the same delay, and turning the LED off. This process is repeated using the DO/LOOP statements. The first program, listed here, writes directly to the P0 I/O pin to turn the LED on and off with delays in between, as described in this paragraph.
images
When doing any kind of programming for the first time, or if you encounter a problem, it is recommended that you try to come up with three different ways of performing a task. The first way, while it works, might not be the most efficient or easily understood method of performing the task. Writing directly to the I/O ports using assignment statements may be confusing to some people. A second way of flashing the LED on and off could be to use the built-in HIGH and LOW PBASIC functions rather than writing to the I/O ports directly. These functions avoid the need for writing to the bits directly:
images
Finally, when looking up the HIGH and LOW functions, you might have discovered the TOGGLE function, which changes the output state of an I/O pin. This feature makes the program even simpler:
images
It is recommended that you play around with the LEDs and try to come up with different applications to demonstrate how the various functions work. For example, you might want to create a Cylon Eye using the eight LEDs using the code:
images
images
Don’t be afraid to try new ideas and if they don’t work, spend some time trying to understand what the problem is and fix it. A good rule of thumb is that your first real program will take two weeks to get running properly, your second program a week, the third two days, the fourth four hours, and so on until you are very familiar with programming the BS2 and looking at different ways of approaching the problems. The Cylon Eye program probably seems very impressive and most likely very difficult to implement on your own, but if you work at the problem, try out different things, and always keep in the back of your mind that you want to think of three different ways of approaching a problem, you will become a competent programmer very quickly.
LEDs, as well as being useful devices for learning how to program, are excellent status indicators for the current state of the program of different inputs. The most basic input device is the momentary on button, which closes the circuit when pressed. This device can be used along with LEDs to demonstrate how digital inputs are passed to the BS2.
The circuit used to test button inputs is shown in Fig. 15-12 and the parts required are listed in Table 15-7. The circuitry was chosen to match that of the previous section to avoid the need to tear down and build up a new circuit as you are learning about the BS2. You may be able to find a momentary on button that can be plugged directly into the breadboard, but chances are you will have to solder some wires to a switch and push them into the breadboard to add the switch to the circuit.
images
 
BS2
Parallax BASIC Stamp 2
LEDs
5 × 2 mm Red LEDs
10k
10k Resistor
Button
Momentary On Button—with wires soldered on to interface with the
breadboard
Programmer
BS2 Programmer/Communications Interface
Misc.
Breadboard, 3x AA Alkaline Battery Clip, Breadboard Wires, Power
Switch

The BS2 is built from CMOS technology. As discussed earlier in the book, it does not have its own internal voltage or current source so you must make sure that the input pins are driven either high or low. In this circuit, the 10k resistor pulls up the input pin until the button is pressed and the pin is connected to ground (pulled down). The 10k resistor limits the amount of current that passes through the momentary on switch to ground to about 50 μA. A pull-up circuit, such as this, should always be used with BS2 inputs to ensure that the voltage always transitions from high to low and a very small amount of current passes between them.
To test the circuit, the following program will turn on the LED at P0 any time the input at P15 is low (which is the pulled up momentary on button). Notice that the value at P15 cannot be passed directly to P0—when the button is pressed, the input is low, but to turn on the LED, the output must be high. The XOR (^ operator) with 1 will invert the signal from P15 so it can be used with P0.
images
When you pushed down the button, you may have noticed that the LED flickered on and off. This was due to button bounce, dirty contacts, or your finger getting tired. To try and show this action more clearly, the second button demonstration turns off all eight LEDs and then starts to turn them on (by shifting bits up) when the button is pressed. If the button is lifted, then the program stops until the button is pressed again.
images
When you ran this program, you probably saw the LEDs cycle up, but occasionally restart or even just flicker to one on. The reasons for this were listed previously and something that will have to be compensated for in your robot control program. Later in the book, you will be shown how to process this information and figure out exactly what is happening but for now just try to work at understanding how to process simple button inputs.
The most effective type of display that you can add to your robot is the liquid crystal display, best known by its acronym LCD. The LCD display allows you to output data in an arbitrary format in alphanumeric or even graphical format to help you understand what is going on within the robot. LCDs have the reputation for being difficult to work with, but there are products such as the Hitachi 44780 controlled LCDs discussed in this section that are quite easy to add and program to a microcontroller.
The 44780 is a chip that is a bridge between a microcontroller and the LCD hardware and was originally manufactured by Hitachi though now it is made by a wide range of chip manufacturers. It contains the four- or eight-bit interface listed in Table. 15-8. In eight-bit mode, all eight bits, D0 through D7, interface to a microcontroller, while in four-bit mode, only the upper four bits (D4 through D7) are used. The other six pins consist of three control and clocking pins, power, and a display contrast voltage.
 
PINS
DESCRIPTION/FUNCTION
1
Ground
2
Vcc
3
Contrast Voltage
4
“RS”-_Instruction/Register Select
5
“RW”-_Write/Read Select
Switch
6
“E” Clock
Switch
7 to 14
Data I/O Pins
Switch
The RS pin selects between passing characters or commands between the LCD and the microcontroller, and the direction of the data is selected by the RW pin. Normally data are sent from the microcontroller to the LCD and not read, so this line is held low. To indicate that the data on the LCD’s pins are correct, the E clock is pulsed from low to high and back to low again. If the LCD is used in four-bit mode, first the four most significant data bits are passed to the LCD, followed by the least significant four data bits.
Data sent to the LCD consists of either instructions (low on RS) or characters (high on RS). The instructions specify how the LCD is to operate and can be used to poll the LCD to determine when to send the next character or command. Table 15-9 lists the different pin and data bit values for sending commands and characters to the LCD.
TABLE 15-9   Hitachi 44780 Command and Data Table
table
More comprehensive information on LCDs can be found on the Internet at the sites listed in the appendices. To demonstrate how simple it is to add and program an LCD to the BS2, the circuit shown in Fig. 15-13 with the parts listed in Table 15-10 was created. The circuit should be very easy to wire together as it was designed for taking advantage of the natural layout of the BS2 as shown in Fig. 15-14
images
 
BS2
Parallax BASIC Stamp 2
LCDs
16 column by 2 row character Hitachi 44780 controlled LCD
10k
10k Potentiometer
Programmer
BS2 Programmer/Communications Interface
Misc.
Breadboard, 3x AA Alkaline Battery Clip, Breadboard Wires, Power
Switch

images
The application code to display “Robot Builder’s Bonanza” on the two rows of the LCD is:
images
images
With the information provided here, you can build and add your own message to an LCD or use it to monitor the progress of a robot. With a bit of research, you can reduce the number of pins required for controlling the LCD as well as demonstrate different capabilities such as changing specific locations on the LCD or adding your own custom characters.
As was noted previously, the second edition of this book presented four different robot control interfaces and one of the strengths of this approach was to use the different controllers for their respective optimal applications and examples. One of the examples for the PC’s parallel port was to provide an I/O pin input/output interface that would allow the reader to see how digital I/O works as well as provide an experimental interface for trying out different hardware interfaces easily.
Along with the usefulness in being able to create a general case I/O interface, there is also the need to better explain all the different ways the BS2’s I/O pins and the associated variables are accessed and what happens. To allow you to arbitrarily read and write to different I/O pins and their variables, “BS2 Port IO.bs2” was created:
images

images

images

images

images

images


This program just requires a running BS2 with a serial port interface. After downloading the code (using Ctrl-R), the debug terminal window will come up and display the introductory message:
images
This menu is a bit cryptic (due to the limitations in the size of the debug terminal display area and the need for additional space for the application code). To net it out, there are three commands that you can enter: “H(elp)” brings up this menu; “I(nput)” will read the contents of a pin variable (which is called a register in this program); and “O(utput)” will write a new value to the pin variable. Only the first character of the command is read and anything else in the command word (ending at a space) is optional.
The pin variables can access the full 16 bits of the pin register (with the variable name ending in S), eight bits (either high or low byte using the L or H postfixes), nibbles, or single bits. When the value in the pin variable is displayed, it is displayed in hexadecimal, binary, and decimal to provide you with the data format that makes the most sense. When writing to the registers, hexadecimal, binary, or decimal values can be specified by leading the value with a $, %, or nothing, respectively.
To access the different registers, add the 16, 8, 1 bit postfix to the register name as shown in Table 15-11 to access the different OUT bits. While all of the 16, 8, and 4 bit labels are shown, only 2 of the possible 16 single bit OUT bit labels are listed.
TABLE 15-11   Different Labels to Access the Different BS2 “OUT” Register Bit Combinations
table
To change the values of a register, use the “O(utput)” command, like
  >   O   DIR0,   1
which puts I/O pin 0 into output mode. To read the state of a pin variable, use the “I(nput)” command
  >   I   OUT0
and the program will display the data.
To demonstrate the operation of the program, wire an LED with its cathode at the BS2’s pin 0 and its anode at pin 3. To turn on the LED, enter the following command sequence. The comments following are to explain what each command is doing.
>   O DIRA,   %1001'Make BS2 Pins 0 & 3 Outputs
>   I   DIRS'Read Back ALL the Mode Bits to See Changes
>   O   OUT3,   1'Turn on the LED
>   I   INL'Read in the lower 8 Bits of the Input Bits
Ironically, even though this application was written for beginners, it is really quite advanced. A large part of this is due to the string parsing that the program performs but a large part is due to trying to shoehorn the application into a BS2 (use Ctrl-M in the BASIC Stamp Editor to see what I mean). The program took a bit of work in figuring out which register was being specified and then what was the value to be written to it.
The BS2 will most likely be the easiest microcontroller or computer system that you will work with. It is easy to program, and the built-in functions allow you to do more with the I/O pins than what you would normally expect to be able to do with a simple microcontroller. Electrically, while the BS2 is very robust, there are a few things that you can do to ensure that it will work reliably and safely in your robot application.
The first thing is to provide an externally regulated 5V to the BS2’s VDD pin rather than some higher voltage on VIN. The on-board regulator’s maximum current output of 100 mA is the reason for suggesting the alternative power input. The voltage regulator has been known to burn out when excessive current is being drawn through the on-board PIC’s I/O pins (for turning on LEDs, for example). The regulator can be replaced, but it is a lot easier to plan for providing 5 V directly to the BS2. The voltage of three AA (or even AAA) alkaline batteries in series is sufficient to power the BS2 along with any external peripherals safely.
In some instances, especially when high voltages are involved, the I/O pins of the BS2 can be damaged. The recommended prevention to this problem is to always put a 220 Ù resistor in series with the I/O pin and whatever devices they are connected to. A 220 Ù resistor will limit the maximum current passing through the I/O pins but still provide enough current to light LEDs. The example circuits in this chapter do not have 220 Ù resistors built into them to simplify the wiring of the sample applications, but when you are installing a BS2 into a robot you should always make sure that you have a resistor on every I/O pin.
There is no need for an external reset control. The BS2’s “_RES” pin is pulled up, so that if you want to add a momentary on button that can tie the pin to ground and reset the BS2 you can. For the most part, this isn’t necessary.
Finally, it is always a good idea to build the BS2’s programming interface into your robot. The circuit is simple and will eliminate the need to pull out the BS2 every time the program is changed. This will reduce the wear and tear on the I/O pins as well as the socket connectors and minimize the chance that you will damage your BS2.
Many of these suggestions are applicable to other microcontrollers and computer interfaces. A few extra parts and a few extra minutes can mean that your competitive robot always will be ready for action, not on the bench waiting for its “brains” to be replaced.