Conditional logic (if / else)
What you’ll learn
if,else ifandelse- Comparison operators
- Combining conditions with and, or and not
if / else if / else
if (distance() < 15) { motors(-50, -50); // very close: back up} else if (distance() < 40) { motors(-40, 40); // close: turn} else { motors(60, 60); // clear: drive}The robot checks the conditions in order and runs the first one that’s true. Put the most specific or most urgent condition first.
Comparisons
| Operator | Means |
|---|---|
< / > |
less than / greater than |
<= / >= |
less or equal / greater or equal |
== (C++) / === (JavaScript) |
equal to |
!= / !== |
not equal to |
Combining conditions
| Operator | Means | Example |
|---|---|---|
&& |
and: both must be true | lineLeft() && lineRight() |
|| |
or: at least one is true | distanceLeft() < 10 || distanceRight() < 10 |
! |
not: flips true and false | !lineLeft() |
Example: three-way decision
int light = analogRead(A0);if (light < 200) Serial.println("dark");else if (light < 700) Serial.println("normal");else Serial.println("bright");Example: order matters
// WRONG: the second branch can never runif (distance() < 40) motors(-40, 40);else if (distance() < 15) motors(-50, -50);
// RIGHT: most urgent firstif (distance() < 15) motors(-50, -50);else if (distance() < 40) motors(-40, 40);Example: and / or
if (lineLeft() && lineRight()) motors(0, 0); // junction: stopif (distanceLeft() < 8 || distanceRight() < 8) motors(-40, -40); // scraping a sideTry it
Robot commands
motors(left, right): wheel power, −100 to 100lineLeft(),lineRight():trueover the black linedistance(): cm to the nearest thing ahead (max 200)distanceLeft(),distanceRight(): cm to the sideslinePosition(): where the line is, −1 (left) to 1 (right), ornullmillis(): milliseconds since Runprint(value): show a message belowsetup()runs once;loop()runs 50 times a second
Cautious driverEasy
Add another level: drive slowly (30) between 40 and 70 cm.
Add else if (distance() < 70) motors(30, 30); before the final else.
Side guardMedium
If either side is closer than 8 cm, steer away from that side.
Show an answer
if (distanceLeft() < 8) motors(60, 20); // wall on the left: steer rightelse if (distanceRight() < 8) motors(20, 60); // wall on the right: steer leftPut these before the forward branch.
Truth tableHard
Write a table for A && !B for all four combinations of A and B.
A=false,B=false → false; A=false,B=true → false; A=true,B=false → true; A=true,B=true → false.
Quick check
Finished this lesson?