Home    Worksheets    Subroutines   'Let' simulator 

Help sheet 114:
Picaxe Basic Maths

This sheet shows you how you can do sums with variables inside the Picaxe.

What is a variable - what is a constant.
The Picaxe has 14 "byte" variables called b0 to b13
They are places where you can save numbers, like the memory function on a calculator.
Constants are simple numbers like "1" or "17" or "%01100000". 
When you use a constant in a program, its value is always the same. 
When you use b0  or b7 in a program the value depends on what was stored there from an earlier part of the program.

How do I store a value into a variable?
To set b0  to have the value 6 use "let b0 = 6"

Maximum value you can store in a variable
"Byte" variables (b0 - b13) can only hold values in the range 0 to 255.
There are other variables (called "word" variables) that can store values bigger than 255.

What Maths can you do in a picaxe? 
You  can Add Subtract Multiply or Divide. There are simple "add 1" and "subtract 1" operators.
"let b0 = b3 + b4"  - adds b3 and b4 and stores the answer in b0.
"let b3 = b3 *  7"  - multiplies b3 by 7 and stores the answer in b3.
"let b1 = b3 - b4"  - subtracts b4  from b3 and stores the answer in b1.
"let b0 = b3 / 3"  - divides B3 by 3 and stores the answer in b0.
"inc b0"  - increases the value of b0 by 1.
"dec b1"  - decreases the value of b1 by 1.

How do I add 1 to a variable?
To add 1 to b3  use either ...
- "let b3 = b3 + 1"  ..
- "inc b3

Where can I use variables?. 
Variables can be used in most places where you would use constants:
for example: 
  "pause b0"
  "let pins = b7"
You have to use a variable immediately after a "let"
You can't use variables for port numbers:   "high b0" is not allowed

What happens when you add 1 to 255.
If you try to store a number greater than 255 into a byte variable (b0-b13) the number is reduced automatically by subtracting 256. 
(If it's still greater than 255 after subtraction, a further 255 is subtracted)
So if you add 1 to 255 you get 0.  if you try to set b0 to 300 you get (300-256 = 44)

What happens when you subtract 1 from 0.
If you try to store a number less than 0 into a byte variable (b0-b13) the number is increased automatically by adding 256. 
(If it's still less than 0 after addition of 256, a further 255 is added)
So if you subtract 1 from  0 you get 255. 

Suppose you want to double the contents of a variable.
...you add it to itself or multiply it by 2
  "let b3 = b3 + b3"    or   "let b3 = b3 * 2" 

Where you can look this up. - see the help pages in programming editor.
Where you can try things out. - use the basic simulator in programming editor.
Where else you can try things out. - use the  'Let' simulator  in these pages.


Content Scl Version 20/04/07