Electronics Projects: How to Use ENDIF and ELSE in PBASIC Code

Programming in PBASIC is a necessary evil when you use programmable microprocessors like the BASIC Stamp in your electronics projects. PBASIC lets you perform logic in your program through the use of IF statements.

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.

A second and more useful form of the IF statement lets you list one or more statements that should 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.

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 must 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 will 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 won’t work properly.

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 that 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.

Here is a version of the LED Flasher program that uses an IF-THEN-ELSE statement to flash the LEDs in sequence.

' 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
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com