OZEKI Robot

Course 2 / Lecture 5:

# Understanding conditions (and using sensors)

In this lecture you will learn and understand how to use if-else statements. It is very important to be able to write conditions, that work with information received from robot sensors. You will practice the syntax, and you will see how to use conditions in different parts of a robot control program.

Figure 1 - Programs about how to use if block

## What is the condition?

Condition - The condition can be anything that return with True or False. You can create condition if you use blocks that can decide from something it is true or false for example with operators.

## Discover the if and if-else blocks!

In this task you will learn where you can find the 'if-else' block and what it is good for and how you can use it. Let's check the 'Control' category. You can see an 'if [condition]' and an 'if [condition] else' block (Figure 2). You can use them if you would like to do something if an event is coming. The 'if-else' block is useful if you would like to do something else if an event is not coming. You can use it easily. Just drop a block into the if block that you would like to do if the [condition] is true.

Figure 2 - 'if' and 'if-else' blocks in Control category

You can communicate with your sensors through chat and SNAP. If you would like to use your sensor through chat you need to send a 'subscribe' to the sensor. If you do not send you can't receive messages from the sensor. In SNAP you have blocks to communicate with them. That blocks contain 'subscribe' so you can use the sensor immediately. Check the 'Lego' category in SNAP. You will find the blocks for sensors here. In this Lecture you will use the Color sensor. For the Color sensor there is a block called 'Color [colour]' (Figure 3).

Figure 3 - Blocks for sensors in SNAP

## Try the 'if' block through a simple program

In this task you will write a simple program to understand how the 'if' block works. The program have to show a happy face if the Color sensor detects red colour and show a sad face if the Color sensor detects green colour. You can write that program easily by using 'if' blocks (Figure 4). The 'if' block's parameters check the colour that the sensor has detected and show a happy or a sad face if the parameter was true so the sensor has detected green or red.

Figure 4 - A simple program using an 'if' block

## Try the 'if-else' block through a simple program

In this task you will learn how you can use the 'if-else' block. You can learn it through a simple program that shows a happy face if the Color sensor detects red colour else there is a sad face on the Brick's screen (Figure 5). In the previous task the Brick didn't show any faces if the colour sensor didn't detect red or green colour but in this case the Brick will show a sad face every time if the sensor don't detect red colour. It is the difference between if and if-else.

Figure 5 - Using 'if-else' block