Learn more with dummies

Enter your email to join our mailing list for FREE content right to your inbox. Easy!

Electronics Projects: How to Do Math in PBASIC Code

By Doug Lowe

A little programming is in order for your electronics project when you use programmable microprocessors like the BASIC Stamp. The BASIC Stamp uses Parallax BASIC (PBASIC). 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 four of these symbols:

X = 10 * 3 / 2 + 5

In this example, the value 20 will be 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 math:

  • 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 would 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. But PBASIC calculates the expression left to right, so it first adds 10 and 3, giving the result 13, and then multiplies the 13 by 2, giving the result 26.

  • You can use parenthesis 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.

  • 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. That’s because 8 divided by 3 is 2 with a remainder of 2. PBASIC discards the remainder and returns the result 2.