Variables and Conditions
Variables:
In computer science, variables are used to store information that the program uses. There are 3 things we can do with variables
In computer science, variables are used to store information that the program uses. There are 3 things we can do with variables
- Create a variables
- assign value
- access the value in the program
Next, to create a variable we need to give it a name. Use the dialog box to name your variable, and click OK. The default "data type" is number. We can now use our variable in our program.
Example:
Create a program that increases a number and displays it every time button A is pressed. Solution: 1. Create your variable and set the value to 0 at the beginning for the program (on start) and display the number on the LEDs 2. Add an input block when button A is pressed. Add 1 to your variable and display it on the LEDs. Try it yourself: Add the code to the makeCode editor and test it. Add code to subtract 1 from the variable when button B us pressed and display it to the LEDs. Download the .hex file. Rename it <lastname> MicroBit 1 and submit it on teams |
Conditional Statements
A Conditional Statement is something we use in coding to change what code is executed based on the value of a variable (a condition).
Generally speaking we can say... if (conditon = true) do something Using the makeCode editor this is found in the logic section of the toolbox. We can compare 2 variables using the inserts from the comparison section Putting them together could look something like this... |
If we wanted to execute different code when myNumber is not 0, it might look like this... (click the + sign to activate an "else" condition. You can add as many you need.
Example:
When the micro:Bit is shaken, use the random number generator (in the math menu) to select a either a 1 or 0. If the number is 1, display a happy face on the LED displays, else display a sad face on the LED displays,
When the micro:Bit is shaken, use the random number generator (in the math menu) to select a either a 1 or 0. If the number is 1, display a happy face on the LED displays, else display a sad face on the LED displays,
Day 5: Micro:bits (loops)
Day 6: Micro:bits(communication)
Day 7: Making a game