Electronics Projects: How to Use IF Statements in PBASIC Code

By Doug Lowe

When you use programmable microprocessors like the BASIC Stamp in your electronics project, a little programming is in order. The BASIC Stamp uses Parallax BASIC (PBASIC), a close cousin to the BASIC programming language and very easy to learn and use. PBASIC lets you perform logic in your program through the 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.

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, like these:

Led < 10
Speed > 1000

Here, 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.

The following program flashes LEDs in sequence. It uses a variable named Led to represent the output pin. 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 sets up the basic loop that first flashes the LED on pin 0, then the LED on pin 2, and then pins 4, 6, and 8, and 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, 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.

' 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 = 50
Led = 0
 PAUSE Speed
 LOW Led
 PAUSE Speed
 Led = Led + 2
 IF Led < 11 THEN Main
 Led = 0
 GOTO Main