Skip to main content

Lesson 5.4: Combining Sensor Checks with AND and OR Logic


Technical Context

Complex robot behaviors often require data from multiple hardware sources to be true simultaneously before an action is taken. Logical combinations improve performance by adding redundancy — for instance, a launcher should only fire if a game element is detected AND the driver confirms the command, preventing "dry firing" that could damage the mechanical tension system.


How AND and OR Change Robot Behavior

Java provides four primary logical operators to combine boolean expressions:

  • && (Logical AND) — requires both sides to be true
  • || (Logical OR) — requires at least one side to be true
  • ! (Logical NOT) — inverts a boolean value
  • ^ (XOR) — true only if the sides differ

Using these operators lets you create complex safety gates. For example, if (isArmRaised && isClawClosed) ensures the robot only drives fast when the center of gravity is stable.


Annotated Code

@Override
public void loop() {
boolean isLoaded = colorSensor.red() > 100;
boolean isAimed = gamepad1.right_trigger > 0.5;

// Combining sensor data (isLoaded) with driver intent (isAimed)
if (isLoaded && isAimed) {
launcher.setPower(1.0); // Fire only if both are true
} else {
launcher.setPower(0.0);
}
}

Fill-in-the-Blank Practice

  1. The operator __________ returns true only if condition A and condition B are both true.
  2. To check if either a sensor is tripped or a button is pressed, the __________ operator should be used.
  3. The __________ operator is used to invert a boolean value, such as changing "Pressed" to "Not Pressed".
Show answers
  1. &&
  2. ||
  3. !

Template Challenge

Robot Scenario: Your robot should only activate the drivetrain if the Start button is NOT pressed AND the Left Trigger is held down more than halfway. (This is a complex safety check.)

Unit 5 simulator
Supports gamepad-driven `if`, `else if`, and `else` logic with live branch visualization.
Includes truth-table and condition-inspector views, plus mock distance and color sensor inputs when needed.
Best for practicing decision logic, thresholds, and simple actuator commands.
Show answer
@Override
public void loop() {
if (!gamepad1.start && gamepad1.left_trigger > 0.5) {
telemetry.addLine("Drive System Active");
drive.setPower(-1 * gamepad1.left_stick_y);
} else {
drive.setPower(0.0);
}
}

Ready to move on?

Sign in with Google to save your progress with Telemark, or continue without saving.