Chapter 2

Programming in PBASIC

In This Chapter

arrow Discovering the essentials of the PBASIC language

arrow Working with variables and constants

arrow Adding IF-THEN-ELSE logic to your programs

arrow Looping with DO and FOR loops

This chapter is about the exciting but somewhat intimidating topic of computer programming. Specifically, it covers programming the BASIC Stamp microprocessor (which we introduce in Chapter 1 of this minibook) using its built-in programming language called PBASIC.

This journey into programming is fascinating but may seem rocky at times, because you need to grasp certain important concepts, which can be difficult to get your head around. But trust us: programming a BASIC Stamp microprocessor isn’t rocket science. You can and will get to grips with the tricky ideas, and when you do your imagination is the only limit to what you can get a BASIC Stamp microprocessor to do.

So grab your thinking cap, check in the mirror that it fits and you look suitably sharp, and get started.

tip.eps PBASIC programming involves much more than this short chapter can cover. For complete information about the PBASIC programming language, download the 500+ page BASIC Stamp Syntax and Reference Manual from www.parallax.com.

Introducing and Using the PBASIC Language

As you can discover in Chapter 1 of this minibook, you use the BASIC Stamp Windows Editor (hereafter referred to simply as the Stamp Editor) to create your programs and download them to the BASIC Stamp.

warning_bomb.eps If you’re unclear on how to do that, please read that chapter before proceeding. You can’t progress very far in PBASIC programming without writing some real programs, downloading them to a BASIC Stamp and observing how they work.

In this chapter, we focus on the PBASIC statements that you use to control BASIC Stamp output pins as well as the statements for controlling the execution of your program. With just the statements used in this chapter, you can set up complicated programs that can control output devices connected to the BASIC Stamp.

For information about how to use BASIC Stamp I/O ports with input devices, please see this minibook’s Chapter 3.



Building a test circuit for the programs

All the programs in this chapter assume that an LED is connected to output pins 0, 2, 4, 6, 8 and 10 of the BASIC Stamp HomeWork board. The programs work with just the even-numbered I/O pins simply because the holes on the breadboard in the BASIC Stamp HomeWork board are too close together to connect LEDs easily to adjacent pins.

Project 2-1 shows how you can build a test circuit that has six LEDs connected to pins 0, 2, 4, 6, 8 and 10 using components that come with the BASIC Stamp Activity Kit, which is available from online electronics stores. You can also easily assemble this circuit with a Board of Education (check out this minibook’s Chapter 1) and your own LEDs and resistors.

Figure 2-1 shows the finished circuit, ready to be used for testing the programs you’re going to write as you work your way through this chapter.

9781118589717-fg070201.tif

Figure 2-1: A BASIC Stamp HomeWork board with six LEDs.

9781118589717-un070201a.eps

9781118589717-un070201b.eps

Flashing the LEDs

In this minibook’s Chapter 1, you see a program that flashes a single LED on and off. In this chapter, we show you several variants of that program, which flash the six LEDs in the test project in various sequences. Along the way, you can add more PBASIC statements to your repertoire to provide more and more complex ways to control the flashing.

remember.eps Keep in mind throughout this chapter that if you can turn an LED on or off with a PBASIC program, you can control anything that can be connected to a BASIC Stamp I/O port. The BASIC Stamp itself doesn’t know or care what kind of circuit you connect to an I/O pin. All it knows is that when you tell it to, the BASIC Stamp makes the I/O port high or low. The external circuitry connected to the pin determines what happens when the pin goes high.

The only limitation is that the BASIC Stamp itself can source only about 20 milliamperes (mA) through its I/O pins. If the circuit connected to the pin requires more current than 20 mA, you have to isolate the higher-current portion of the circuit from the BASIC Stamp. The easiest way to do so is by using a transistor driver or a relay.

Listing 2-1 shows a simple program that flashes all six LEDs on and off at half-second intervals. This program uses nothing more than the HIGH, LOW, PAUSE and GOTO statements that we present in this minibook's Chapter 1. The program turns all six LEDs on, pauses for 500 milliseconds (ms; half a second), turns the LEDs off, waits another half-second and then jumps back to the Main label to start the whole process over. (The numbers and arrows to the right are not part of the program but are annotations which we explain after Listing 2-1.)

Listing 2-1: Flashing LEDs

' {$PBASIC 2.5} → 1

' {$STAMP BS2} → 2

 

Main: → 4

HIGH 0 → 5

HIGH 2

HIGH 4

HIGH 6

HIGH 8

HIGH 10

PAUSE 500 → 11

LOW 0 → 12

LOW 2

LOW 4

LOW 6

LOW 8

LOW 10

PAUSE 500 → 18

GOTO Main → 19

The following paragraphs summarise the operation of this program:

1 This line indicates that the program is written in version 2.5 of PBASIC. Every program you write for the BASIC Stamp 2 has to include this line. We describe how to insert it automatically into a program in Chapter 1 of this minibook.

2 This line indicates that the program is going to run on a BASIC Stamp 2, and it’s required for every program you run on a BASIC Stamp 2 microcontroller. You can insert it automatically by choosing Directive⇒Stamp⇒BS2.

4 The label Main: identifies the location to which the GOTO statement in line 19 jumps. Main: is known as a label, which is simply a named location in your program. To create a label, you just type a name followed by a colon. For more information about creating value names in PBASIC, see the section 'Creating Names' later in this chapter.

5 This line sets the output of pin 0 to high, which in turn lights up the LED. The following lines (6 through 10) similarly turn on pins 2, 4, 6, 8 and 10.

11 This line pauses the program for 500 ms (half a second).

12 This line and the five that follow set the outputs of pins 0, 2, 4, 6, 8, and 10 to low, which in turn extinguishes the LEDs.

18 This line pauses the program for an additional half-second.

19 This line transfers control of the program back to the Main label in line 4 so that the program repeats.

Commenting to Clarify Your Code

A comment is a bit of text that provides an explanation of your code. PBASIC completely ignores comments, and so you can put any text you want in a comment. Using plenty of comments in your programs to explain what your program does and how it works is a good idea.

remember.eps A comment begins with an apostrophe. When PBASIC sees an apostrophe on a line, it ignores the rest of the line. Thus, if you place an apostrophe at the beginning of a line, the entire line is considered to be a comment. If you place a comment in the middle of a line (for example, after a statement), everything after the apostrophe is ignored.

Common programming practice is to begin a program with a group of comments that indicates what the program does, who wrote it and when. This block of comments should also indicate what I/O devices are expected to be connected to the BASIC Stamp. Listing 2-2 shows a version of the LED Flasher program (from the preceding section) that includes both types of comments.

technicalstuff.eps You may notice that the $PBASIC and $STAMP directives begin with an apostrophe. Technically, these lines are treated as comments.

Listing 2-2: LED Flasher with Comments

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' at one-half second intervals.

 

' {$PBASIC 2.5}

' {$STAMP BS2}

 

Main:

HIGH 0 'Turn the LEDs on

HIGH 2

HIGH 4

HIGH 6

HIGH 8

HIGH 10

PAUSE 500 'Wait one-half second

LOW 0 'Turn the LEDs off

LOW 2

LOW 4

LOW 6

LOW 8

LOW 10

PAUSE 500 'Wait one-half second

GOTO Main

Creating Names in your Programs

In PBASIC, you can create your own names to use as program labels and for constants and variables (check out the later ‘Employing Constants as Substitute Values’ and ‘Creating Variables to use RAM Memory’ sections). You can also give a name of your own to I/O pins, which makes remembering what kind of input or output is expected from each pin easier (see the section ‘Assigning Names to I/O Pins’ later in this chapter).

remember.eps

You need to follow a few simple rules when creating names in PBASIC:

check.png Names can consist of a combination of upper- and lowercase letters, numbers and underscore characters (_). Other special characters, such as dollar signs or exclamation marks, aren't allowed. Thus, Timer_Routine and Relay7 are valid names, but LED$ or Bang! aren't.

check.png Names have to begin with a letter or an underscore but can't begin with a number. Thus, Timer1 and _Timer1 are valid names, but not 1Timer.

check.png Names may be as long as 32 characters.

check.png Names aren't case-sensitive, which is to say that PBASIC doesn't distinguish between upper- and lowercase letters. Thus, PBASIC considers all the following names to be identical: TimerCheck, timercheck, TIMERCHECK and TiMeRcHeCk.

tip.eps Although nothing in PBASIC is case-sensitive, and you can write anything in upper- or lowercase, common PBASIC programming convention is that keywords such as HIGH and GOTO are written in all caps, while names are written with just the first letter capitalised.

Employing Constants as Substitute Values

A constant is a name that has been assigned a value, which allows you to use the constant name in your program rather than the value itself. Later, if you decide to change the value, you don’t have to hunt through the program to find every occurrence of the constant. Instead, you simply change the line that defines the constant.

Here's a statement that creates a constant named Delay and assigns the value 500 to it:

Delay CON 500

The CON keyword indicates that Delay is a constant whose assigned value is 500.

To use a constant, just substitute the name of the constant wherever you'd use the value. For example, the following line pauses the program for the value assigned to the Delay constant:

PAUSE Delay

Listing 2-3 shows a version of the LED Flasher program that uses a constant to determine how fast the LEDs are going to flash.

Listing 2-3: The LED Flasher Program with a Constant

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' at one-half second intervals.

'

' This version of the program uses a constant

' for the time interval.

 

' {$PBASIC 2.5}

' {$STAMP BS2}

 

Delay CON 500

 

Main:

HIGH 0

HIGH 2

HIGH 4

HIGH 6

HIGH 8

HIGH 10

PAUSE Delay

LOW 0

LOW 2

LOW 4

LOW 6

LOW 8

LOW 10

PAUSE Delay

GOTO Main

Assigning Names to I/O Pins

You can use the HIGH and LOW statements to set the output status of an I/O pin. For example, the following statement sets pin 6 to high:

HIGH 6

Here, the number 6 indicates that pin 6 is to be set to high.

The problem with using just the pin number to identify which pin you want to control is that you can’t tell what kind of device is connected to pin 6 simply by looking at the statement. It may be an LED, but it may also be a motor or a servo or even a pneumatic valve that causes a Frankenstein creature to pop up.

To remedy this situation, PBASIC lets you assign a name to an I/O pin by placing a statement similar to this one near the beginning of your program:

Led1 PIN 0

Here, the name Led1 is assigned to pin 0. Now, you can use the name Led1 in a HIGH or LOW statement, as follows:

HIGH Led1

This statement sets the I/O pin referenced by the name Led1 to high.

tip.eps Listing 2-4 shows a version of the LED Flasher program that uses pin names instead of the pin numbers. The real advantage of creating pin names is that changing the pin configuration of your project later on becomes much easier.

For example, suppose that you decide that instead of connecting the six LEDs to pins 0, 2, 4, 6, 8 and 10, you want to connect them to pins 0, 1, 2, 3, 4 and 5. By using pin names, you need to change the pin assignments just once when you modify the program, in the PIN statements near the beginning of the program.

Listing 2-4: The LED Flasher Program with Pin Names

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' at one-half second intervals.

'

' This version of the program uses pin names instead of numbers.

 

' {$PBASIC 2.5}

' {$STAMP BS2}

 

Led1 PIN 0

Led2 PIN 2

Led3 PIN 4

Led4 PIN 6

Led5 PIN 8

Led6 PIN 10

 

Main:

HIGH Led1

HIGH Led2

HIGH Led3

HIGH Led4

HIGH Led5

HIGH Led6

PAUSE 500

LOW Led1

LOW Led2

LOW Led3

LOW Led4

LOW Led5

LOW Led6

PAUSE 500

GOTO Main

Creating Variables to Use RAM Memory

The BASIC Stamp 2 microprocessor has 32 bytes of RAM memory available for your programs to use. That may not sound like a lot, but it’s plenty of RAM for most of the programs you’re likely to create for your BASIC Stamp projects.

To use RAM memory in PBASIC, you create variables. A variable is simply a name that refers to a location in RAM. When you’ve created a variable, you can use the variable name in your program code to set or retrieve the value of the variable, and you can use the variable name in expressions, which perform simple mathematical calculations on the value of variables.

remember.eps To create a variable, you list the name you want to use for the variable, followed by the keyword VAR, followed by one of four keywords that indicates the type of the variable you're creating. For example, the following creates a variable named Count, using the variable type BYTE:

Count VAR BYTE

Here are the four options for the variable type:

check.png BIT: Uses just one binary bit. Thus, the BASIC Stamp can squeeze up to eight BIT variables in each of its 32 bytes of available RAM. BIT variables are mostly used to keep track of whether some event has occurred. For example, you can set up a BIT variable to remember whether a user has pressed an input button. The value 0 indicates that the button hasn't yet been pressed and the value 1 means that the button has been pressed.

check.png BYTE: Uses one of the 32 available bytes of RAM and can have a value ranging from 0 to 255. This type of variable is useful for simple counters that don't need to exceed the value 255. For example, if you're creating a timer to count down 60 seconds, a BYTE variable does the trick.

check.png NIB: If you have a very small counter whose value is never going to exceed 15, you can use a NIB variable, which requires only one-half of one byte of RAM. Thus, in theory you can create as many as 64 different NIB variables in a BASIC Stamp 2's 32 bytes of RAM.

check.png WORD: Uses two of the 32 available bytes and can have a value ranging from 0 to 65,535. You need to use a WORD variable whenever the value to be stored in the variable is greater than 255. For example, a WORD variable is ideal for holding the length of a delay used by the PAUSE statement.

When you've created a variable, you can use it in an assignment statement to assign it a value. An assignment statement consists of a variable name followed by an equals sign, followed by the value to be assigned. For example, this assignment statement assigns the value 500 to a variable named Delay:

Delay = 500

The value on the right side of the equals sign can be an arithmetic calculation. For example:

Delay = 500 + 10

In this example, the value 510 is assigned to the variable named Delay.

Little point exists in doing arithmetic using only numerals; after all, you can do the calculation yourself. Thus, the previous example can be written as follows:

Delay = 510

tip.eps The real power of variable assignments happens when you use variables on the right side of the equals sign. For example, the following statement increases the value of the Delay variable by 10:

Delay = Delay + 10

In this example, the previous value of Delay is increased by 10. For instance, if the Delay variable's value was 150 before this statement executed, it becomes 160 after.

Listing 2-5 shows a program that uses a variable to change the speed at which the LEDs flash each time the GOTO statement causes the program to loop. As you can see, a variable named Delay is used to provide the number of milliseconds that the PAUSE statement is to pause. Each time through the loop, the value of the Delay variable is increased by 10. Thus, the LEDs flash very quickly when the program starts, but the flashing gets progressively slower as the program loops.

Listing 2-5: The LED Flasher Program with a Variable

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' at one-half second intervals.

'

' This version of the program uses a variable delay.

 

' {$PBASIC 2.5}

' {$STAMP BS2}

 

Led1 PIN 0

Led2 PIN 2

Led3 PIN 4

Led4 PIN 6

Led5 PIN 8

Led6 PIN 10

 

Delay VAR Word

Delay = 10

 

Main:

HIGH Led1

HIGH Led2

HIGH Led3

HIGH Led4

HIGH Led5

HIGH Led6

PAUSE Delay

LOW Led1

LOW Led2

LOW Led3

LOW Led4

LOW Led5

LOW Led6

PAUSE Delay

Delay = Delay + 10

GOTO Main

tip.eps PBASIC lets you use a variable in a HIGH or LOW statement to indicate which pin is to be controlled. For example:

Led VAR BYTE

Led = 0

HIGH Led

This sequence of statements creates a variable named Led, assigns the value 0 to it and then uses it in a HIGH statement. The result is that I/O pin 0 is set to high.

Carrying out Maths Functions

PBASIC lets you perform addition, subtraction, multiplication and division using the symbols (called operators) +, –, * and /. Here’s an example of an assignment that uses all some of these symbols:

X VAR BYTE

X = 10 * 3 / 2 + 5

In this example, the value 20 is assigned to the variable X (10 × 3 = 30, 30 / 2 = 15, and 15 + 5 = 20).

Here are a few things you need to know about how PBASIC does maths:

check.png Unlike most programming languages, PBASIC performs mathematical operations strictly on a left-to-right basis. For example, consider the following assignment:

X = 10 + 3 * 2

Most programming languages first multiply the 3 by the 2, giving a result of 6, and then add the 6 to the 10, giving the final result 16. That’s because multiplication is ordinarily done before addition in equations. But PBASIC calculates the expression left to right, and so it first adds 10 and 3, giving the result 13, and then multiplies the 13 by 2, giving the result 26.

check.png You can use parentheses to force PBASIC to calculate a certain part of the formula first. For example:

X = 10 + (3 * 2)

Here, PBASIC first does the calculation inside the parenthesis, giving a result of 6. It then adds the 6 to the 10 to give the final result, 16.

check.png When PBASIC does division, it discards the remainder and returns the result as a whole number. For example:

X = 8 / 3

This statement assigns the value 2 to X, because 8 divided by 3 is 2 with a remainder of 2. PBASIC discards the remainder and returns the result 2.

Making use of IF Statements

An IF statement lets you add conditional testing to your programs. In other words, it lets you execute certain statements only if a particular condition is met. This type of conditional processing is an important part of any but the most trivial of programs.

remember.eps Every IF statement must include a conditional expression that lays out a logical test to determine whether the condition is true or false. For example:

X = 5

This condition is true if the value of the variable X is 5. If X has any other value, the condition is false.

You can use less-than or greater-than signs in a conditional expression, as follows:

Led < 10

Speed > 1000

The first expression is true if the value of Led is less than 10. The second expression is true if the value of Speed is greater than 1,000.

In its simplest form, the IF statement causes the program to jump to a label if a condition is true. For example:

IF Led < 11 THEN Main

Here, the program jumps to the Main label if the value of the Led variable is less than 11.

Listing 2-6 shows a program that flashes the LEDs in sequence. This program uses a variable named Led to represent the output pin to be used. On each pass through the loop, it adds 2 to the Led variable to determine the next LED to be fired. Then, an IF statement is used to loop back to the Main label if the Led variable is less than 11. This design sets up the basic loop that first flashes the LED on pin 0, and then the LED on pin 2, and then pins 4, 6 and 8, and finally 10.

After the program flashes the LED in pin 10, the program adds 2 to the Led variable, setting this variable to 12. Then, the conditional expression in the IF statement (X < 11) tests false instead of true, and so the IF statement doesn't skip to the Main label at this point. Instead, the statement after the IF statement is executed, which resets the Led variable to zero. Then, a GOTO statement sends the program back to the Main label, where the first LED is flashed again.

Listing 2-6: The LED Flasher Program with an IF statement

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' in sequence.

'

' This version of the program uses a simple IF statement.

 

' {$PBASIC 2.5}

' {$STAMP BS2}

 

Speed VAR BYTE

Led VAR BYTE

 

Speed = 50

Led = 0

 

Main:

HIGH Led

PAUSE Speed

LOW Led

PAUSE Speed

Led = Led + 2

IF Led < 11 THEN Main

Led = 0

GOTO Main

A second and more useful form of the IF statement lets you list one or more statements to be executed if the condition is true. For example:

IF Led < 10 THEN

Led = Led + 2

ENDIF

In this example, 2 is added to the Led variable if the value of the Led variable is less than 10.

You can place as many statements as you want between the IF and ENDIF statements. For example:

IF Led < 10 THEN

Speed = Speed + 10

Led = Led + 2

ENDIF

Here, the Speed variable is also increased if the condition expression is true.

remember.eps The main difference between the IF statement with ENDIF and an IF statement without ENDIF, is that without the ENDIF the statement that's executed if the IF condition is true has to be on the same line as the IF and THEN keywords. If the THEN keyword is the last word on a line, PBASIC assumes that you're going to use an ENDIF to mark the end of the list of statements to be executed if the IF condition is true. If you forget to include the ENDIF statement, the program doesn't work properly.

tip.eps One last trick that the IF statement lets you do is list statements that you want to execute if the condition isn't true. You do so by using an ELSE statement along with the IF statement. For example:

IF Led < 10 THEN

Led = Led + 2

ELSE

Led = 0

ENDIF

Here, Led is increased by 2 if its current value is less than 10. But if the current value of Led isn't less than 10, the Led variable is reset to 0.

Listing 2-7 shows a version of the LED Flasher program that uses an IF-THEN-ELSE statement to flash the LEDs in sequence.

Listing 2-7: LED Flasher with an IF-THEN-ELSE statement

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' in sequence.

'

' This version of the program uses an IF-THEN-ELSE statement.

 

' {$PBASIC 2.5}

' {$STAMP BS2}

 

Speed VAR BYTE

Led VAR BYTE

 

Speed = 50

Led = 0

 

Main:

HIGH Led

PAUSE Speed

LOW Led

 

PAUSE Speed

IF Led < 10 THEN

Led = Led + 2

ELSE

Led = 0

ENDIF

GOTO Main

Pressing DO Loops into Service

The DO loop is a special PBASIC statement that performs essentially the same function as a label and a GOTO statement (check out the earlier section 'Flashing the LEDs'). For example, consider the following:

 

Main:

HIGH 0

PAUSE 500

LOW 0

PAUSE 500

GOTO Main

You can accomplish the same function without the Main label or the GOTO statement by placing the lines that turn the LED on and off between DO and LOOP statements, as follows:

 

DO

HIGH 0

PAUSE 500

LOW 0

PAUSE 500

LOOP

The lines between the DO and LOOP statements are executed over and over again indefinitely.

Listing 2-8 shows the LED Flasher program implemented with a simple DO loop instead of a label and a GOTO statement.

Listing 2-8: LED Flasher with a DO loop

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' in sequence.

'

' This version of the program uses a DO loop.

 

' {$PBASIC 2.5}

' {$STAMP BS2}

 

Speed VAR BYTE

Led VAR BYTE

 

Speed = 50

Led = 0

 

DO

HIGH Led

PAUSE Speed

LOW Led

PAUSE Speed

IF Led < 10 THEN

Led = Led + 2

ELSE

Led = 0

ENDIF

LOOP

You can add a conditional test (for details, flip to the earlier section 'Making use of IF Statements') to the LOOP statement to make the loop conditional. For example:

Led = 0

DO

HIGH Led

PAUSE 500

LOW Led

PAUSE 500

Led = Led + 2

LOOP UNTIL Led > 10

This code flashes the LEDs on pins 0, 2, 4, 6, 8 and 10. After the LED on pin 10 is flashed, the next-to-last line sets the Led variable to 12. Then, the LOOP UNTIL statement sees that Led is greater than 10, and so it stops looping.

Instead of the word ­UNTIL, you can use the word WHILE to mark the condition in a DO loop. A substantial difference exists between UNTIL and WHILE, just as the words suggest:

check.png UNTIL: The loop executes until the condition tests true.

check.png WHILE: The loop executes until the condition tests false.

tip.eps You can also include the conditional test on the DO statement or on the LOOP statement:

check.png If you place the conditional test on the DO statement, the condition is tested before each execution of the loop.

check.png If you place it on the LOOP statement, the condition is tested after the completion of each loop.

A common programming technique is to place WHILE tests on the DO statement and UNTIL tests on the LOOP statement. For example:

Led = 0

DO WHILE Led < 11

HIGH Led

PAUSE 500

LOW Led

PAUSE 500

Led = Led + 2

LOOP

Here, the value of Led is tested prior to each execution of the loop. The loop is executed as long as Led is less than 11.

tip.eps You can nest DO loops, which simply means that one DO loop can contain another DO loop. Note that when you nest DO loops, the inner loop must have a conditional test (see the earlier 'Making use of IF Statements' section). Otherwise, it loops forever and the outer loop never has a chance to complete.

Listing 2-9 shows a program that uses two nested DO loops to flash the LEDs in sequence. The innermost DO loop flashes the six LEDs once. It uses an UNTIL condition to stop the loop after the last LED has flashed. The outermost DO loop continues endlessly, causing the flashing sequence to continue indefinitely.

Listing 2-9: The LED Flasher Program with Nested DO Loops

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' in sequence.

'

' This version of the program uses nested DO loops.

 

' {$PBASIC 2.5}

 

' {$STAMP BS2}

 

Speed VAR BYTE

Led VAR BYTE

 

Speed = 50

 

DO

Led = 0

DO

HIGH Led

PAUSE Speed

LOW Led

PAUSE Speed

Led = Led + 2

LOOP UNTIL Led > 10

LOOP

Keeping Count with FOR Loops

A FOR loop is a special type of looping statement that automatically keeps a counter variable. FOR loops are ideal when you want to execute a loop a certain number of times or when you want to perform an action on multiple I/O pins. Therefore, a FOR loop is the ideal way to implement the LED Flasher program.

Here's the basic structure of a FOR loop:

FOR counter = start-value TO end-value

Statements...

NEXT

Here’s an example that flashes the LED on pin 0 ten times:

X VAR BYTE

FOR X = 1 TO 10

HIGH 0

PAUSE 500

LOW 0

PAUSE 500

NEXT

In this example, the loop is executed ten times. The value of the variable X is increased by 1 each time through the loop.

In the preceding example, the program didn't use the counter variable, which is common in FOR loops; sometimes the only purpose for the counter variable is to control how many times the loop is executed. But you can use the counter variable within the loop. For example, here's a loop that makes every I/O pin on the Stamp high for one-tenth of a second:

IO_Pin VAR BYTE

FOR IO_Pin = 0 TO 15

HIGH IO_Pin

PAUSE 100

LOW IO_Pin

NEXT

tip.eps Normally, the counter variable is increased by 1 on each pass through the loop. You can use the STEP keyword to specify a different step value if you want. When you use the STEP keyword, the basic structure of the FOR statement is as follows:

FOR counter = start-value TO end-value STEP step-value

Statements...

NEXT

For example, you can flash LEDs on just the even-numbered pins as follows:

Led VAR Byte

FOR Led = 0 TO 10 STEP 2

HIGH Led

PAUSE 100

LOW Led

NEXT

tip.eps Another interesting feature of FOR loops is that they can count backward. All you have to do is specify a start value that's larger than the end value:

Led VAR Byte

FOR Led = 10 TO 0 STEP 2

HIGH Led

PAUSE 100

LOW Led

NEXT

Listing 2-10 shows a version of the LED Flasher program that uses a pair of FOR loops to flash the LEDs first in one direction and then in the opposite direction. The created effect is similar to the spooky electronic eyes on the evil Cylons in the old TV series Battlestar Galactica. The first FOR loop flashes the LEDs on pins 0, 2, 4, 6 and 8. Then the second FOR loop flashes the LEDs on pins 10, 8, 6, 4 and 2. Both FOR loops are contained within a DO loop that keeps the LEDs bouncing back and forth indefinitely.

Listing 2-10: The LED Flasher Program with FOR Loops

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' back and forth, like Cylon eyes.

'

' This version of the program uses FOR loops.

 

' {$STAMP BS2}

' {$PBASIC 2.5}

 

Led VAR Byte

 

Main:

FOR Led = 0 TO 8 STEP 2

HIGH Led

PAUSE 100

LOW Led

NEXT

FOR Led = 10 TO 2 STEP 2

HIGH Led

PAUSE 100

LOW Led

NEXT

GOTO Main

Like DO loops (which we discuss in the preceding section), you can nest FOR loops. When you nest FOR loops, the innermost loop(s) complete their entire cycle each time through the outer loop. In other words, if a FOR loop that repeats 10 times is placed within an outer loop that repeats 10 times, the statements within the innermost loop execute a total of 100 times – 10 times for each of the 10 repetitions of the outer loop.

Listing 2-11 shows a variation on the Cylon eyes program in Listing 2-10. This one uses an outer FOR loop that varies the delay time for the PAUSE statements. The result is that the LEDs sweep very quickly at first, but slow by 10 ms on each repetition of the outer loop until the delay reaches 1 second per LED.

Listing 2-11: The LED Flasher Program with Nested FOR Loops

' LED Flasher Program

' Doug Lowe

' July 10, 2011

'

' This program flashes LEDs connected to pins 0, 2, 4, 6, 8, and 10

' back and forth, like Cylon eyes.

'

' This version of the program uses nested FOR-NEXT loops to slow the

' sweeping motion of the LEDs.

 

' {$STAMP BS2}

' {$PBASIC 2.5}

 

Led VAR Byte

Speed VAR Word

 

FOR Speed = 10 TO 1000 STEP 10

FOR Led = 0 TO 8 STEP 2

HIGH Led

PAUSE Speed

LOW Led

NEXT

FOR Led = 10 TO 2 STEP 2

HIGH Led

PAUSE Speed

LOW Led

NEXT

NEXT

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset