Introduction to Logic
What is Logic?
In programming, logic refers to a set of rules we create within the code for the robot to follow. It allows the robot to make decisions based on the information it gathers rather than going only through a single step-by-step process of execution.
In Blocks, the Logic menu includes options to create comparison statements, like to check if one thing is greater than the other, and the option to make something the opposite with the "not" block. But for this section we'll be focusing on if/else Statements!

If/Else Statements
One of the key concepts of logic in programming are if/else statements, also referred to as if/then statements.
In its most simple format an if/else statement asks the robot to check IF something is happening and if the answer is yes, or true in the robot's mind, THEN it will DO what has been asked.

In this format, the robot hasn't been told what to do if the statement is false. That's where the else comes in to play. Same as before the robot checks IF something is true, and if so, THEN executes a command, ELSE it executes a different command.

Let's look at an example. Looking at the code below, the robot is checking IF the gamepad's A button has been pressed. If the check returns true, meaning the button is pressed, THEN it will spin the servo at a power of 1, but if it returns false the servo's power will be set to 0.

Else If
Multiple things can be checked at once, such as various buttons on a gamepad, by expanding the statement to include an else if:

By adding an else if, our robot now has multiple things to check for if it's true or false.
In the following example, we've added to our check for if A is pressed on the gamepad to alternatively check if B is pressed. IF B is pressed, THEN the servo will spin in reverse at -1 power. Our else remains the same so the servo turns off if neither button is pressed.

Try creating this program yourself and give it a try!

Consider:
What happens when A or B is pressed?
What happens if both are pressed at the same time?
What happens if we control a different actuator with B?
Editing If/Else Statements in Blocks
In Blocks, there are only a few if/else statements available by default:

But, if we need something different then we can click the blue gear icon to customize the if/else block!

We can add multiple else if options to expand the statement as long as we need.

Keep in mind, there's appropriate times for when to have checks all together in one statement and when to have multiple individual statements. What works best will vary per project, person, and how an OpMode is organized.
Last updated
Was this helpful?

