5 Variables

Saving a number in a Variable

The most basic operation of any computer language is assigning a number to a variable, which is the same a saving a number into memory. To do this simple operation using the mpy Language you simply write:

a = 3

Here the number 3  is saved into a variable called  a ,  or we say that variable a is assigned the value 3

Variable Names

A variable name can be any name that starts with a letter.  A variable name can be a single letter like a, or it can be a word like  count , it can also have underscore _ characters in it, like max_value.  A variable name cannot have any spaces in it. Variables with uppercase characters are different to variables using lowercase characters, e.g. variable Max_Value and variable max_value are two completely different variables.  Names in mpy are case-sensitive.  Getting uppercase variable names mixed up with lowercase ones is a common cause of errors. It is common to use lowercase names for variable names with underscores _ , if you stick to using lowercase then you are less likely to make this type of mistake.

Copying Variables

You can assign the values of one variable into another variable, like:

a = 3
b = a

This makes the value of b equal to 3

All Variables are Integers

All variables in mpy are integers (or whole numbers),  and all arithmetic in mpy produces results which are integers.

Furthermore all mpy numbers are restricted in range from  -32768 to +32767. This is because the MSP430 microcontroller has a 16 bit wide data bus. (With only 16 bits the maximum range of numbers  that can be  defined is 2 raised to the power 16, so any number in the range 0 to 65536 can be defined, but in mpy we use -32768 to +32767 which is the same range but shifted so that negative numbers and positive numbers are available, which is a more useful when writing programs)

This means that adding two large numbers can result in a sum that is too large to store in a variable and can produce the wrong result. For example you would expect 20000 + 30000 to give the answer 50000, but 50000 is greater than +32767 and cannot be stored in a mpy variable, instead the sum  overflows and produces the answer -15536 . A similar thing happens when the sum produces a number less than -32768. Be careful not to let your numbers overflow, otherwise you will get unexpected results.

Another consequence of using integers is that when you divide one number by another the answer will also be an integer. So the sum   a = 7/3  =  2 , it should be 2.3333,  but mpy numbers are integers and so the answer is rounded down to 2.  Also  a = 1/2 = 0 , it should be 0.5 but again it is rounded down to give an answer of 0.