micro:bit Programming - Make an if statement with a robot
June 29, 2018
An if then statement is one of the easiest logic statements you can use when programming the micro:bit. In this case, we'll have our robot do something only if something is true!
What's an If Statement?
An if statement is a very simple logical idea. If you want something done by your robot or your computer, you use an if statement.
You probably use if statements in your life all the time. For example:
"if it's raining, bring and umbrella with you to school."
Or, maybe you have the if-statement:
"If the dog is barking, feed it food."
We use simple if-statements like this in programming computers and robots all the time.
Programming an If Statement
In this case, we're going to program an if statement for a robot. Let's say we want the robot to move forward for 1 second, if we press a button. In English we would say:
"If button A on the micro:bit is pressed, drive forward for 1 second."
That's how we'd say it in English, how would we say it in MakeCode?
How do you program an if-statement in MakeCode?
Find the If-Statement
You can find the if statement under the "logic" section in the palette. It is the first and most basic function in the section.
Alternatively you can also search for it. Start typing "if" into the search area and the basic if-statement is the first to come to the top.
Either way, drag the if-statement onto the workspace.
Change the Logic
Next we're going to change the logic. Right now our statement is always true. We need something that is sometimes true and sometimes false. We'll replace the "true" piece with a button-logic-piece.
Change the Action
Now let's give the block some action. When A is pressed want it to drive forward. So we'll add in the drive forward command for the GiggleBot.
Robots Moving Forward When Button Is Pressed
The final code will move the robot forward IF the button is pressed!
Going Further with the GiggleBot
If you want to learn more coding, check out our coding examples for the micro:bit and GiggleBot here!