IF…THEN…ELSE

BS2 icon BS2e icon BS2sx icon BS2p icon BS2pe icon BS2px icon {PBASIC 2.5}

IF...THEN...ELSE Example

 

 

 

Syntax:

   IF Condition THEN
     Statement(s)
 { ELSEIF Condition(s) THEN
     Statement(s) }
 { ELSE
     Statement(s) }
   ENDIF

   IF Condition THEN Statement(s){ ELSEIF Statement(s) } { ELSE Statement(s) }

Function

Evaluate Condition and, if it is true, execute the statement(s) following THEN, otherwise jump to and evaluate the ELSEIF condition. If no ELSEIF statement/block is provided, jump to and execute the statements that follow ELSE. If no ELSE block is provided, the program will continue at the line that follows ENDIF (or the next line when single-line syntax is used).

Quick Facts

  BS2 Family
Comparison operators =, <>, >, <, >=, <=
Conditional Logic Operators NOT, AND, OR, XOR
Format of condition Value1 Comparison Value2;
where Value1 and Value2 can be any of variable, constant or expression
Parentheses Allowed
Nesting Up to 16 levels
Related Commands

IF…THEN, SELECT...CASE

Explanation

IF...THEN...ELSE is a primary PBASIC decision maker that allows one block of code or [optionally] another to run based on the value (True or False) of a condition. The condition that IF...THEN...ELSE tests is written as a mixture of comparison and logic operators. The available comparison operators are:

Comparison Operator Symbol Definition
= Equal
<> Not Equal
> Greater Than
< Less Than
>= Greater Than or Equal To
<= Less Than or Equal To

 

Comparisons are always written in the form: Value1 Comparison Value2. The values to be compared can be any combination of variables (any size), constants, or expressions.

value   VAR     Word

Main:
  DO
    PULSIN 0, 1, value                          ' measure pulse input
    DEBUG DEC value, CR
    IF (value > 4000) THEN                      ' evaluate duration
      DEBUG "Value was greater than 4000"
    ELSEIF (value = 4000) THEN
      DEBUG "Value was equal to 4000"
    ELSE
      DEBUG "Value was less than 4000"
    ENDIF
    DEBUG CR, CR
    PAUSE 1000
  LOOP

Here, the BASIC Stamp will look for and measure a pulse on I/O pin 0, then compare the result, value, against 4000. Based on this comparison, a message regarding the pulse width value will be printed.

In the following example, single-line syntax is used. Note that ENDIF is not required when using single-line formatting of IF...THEN...ELSE:

  DEBUG "Your grade is: "
  IF (score >= 90) THEN DEBUG "A", CR : ELSE DEBUG "B (or less)", CR

See IF…THEN for additional details on the use of comparison and conditional operators.

Go to PBASIC Language home page

Open Getting Started with Stamps in Class

Open Connection Troubleshooting

BASIC Stamp Help Version 2.5.4

Copyright © Parallax Inc.

8/21/2013