When we count we need to remember what number we are up to so we can add the next number. When we were little we may have used our fingers to help us remember. Computers use variables.
A variable is a space in the computer's memory that we can store data. We give that space a name so we can quickly get to that data.
When using variable we often need to:
put data into the variable
change the data in the variable
get the data from the variable
So far in our programming of the microbit we have looked at input, processing and output, but we have yet to use storage!
Go to the variables menu and click
'Make a Variable'
Give the variable a suitable name so you know what data the variable will hold.
Some new blocks will appear!
These blocks all say 'count' because that is the name that was given in this example, but they called anything.
Set 'count' to '0'
puts a value into the variable
change 'count' by '1'
will add the number to value already in the variable. If the number is negative it will take it away.
'count'
is used to get the value from the variable.
The program below shows how you can use a variable to count.
It starts by assigning a value to count. It sets the number to 0. It then shows the number in the variable on the LEDs
When the A button is pressed, it changes the number in the variable by 1 (it adds 1 to the number). It then shows an image to show the user that it has added 1.
When the B button is pressed, it shows the number in the variable on the LEDs
Watch the video below to see how to make a variable. assign a value then use it to count.
Create a program that:
When it starts:
assigns the number 5 to a variable
shows the number in the variable
When you press 'A' takes away 1 from the value of the variable
When you press 'B' adds 1 to the value of the variable
When you press 'A' & 'B' shows the number in the variable
A named place in memory where data can be stored and changed whilst a program is running.
Putting a piece of data into a variable