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 betrue||(Logical OR) — requires at least one side to betrue!(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
- The operator
__________returnstrueonly if condition A and condition B are bothtrue. - To check if either a sensor is tripped or a button is pressed, the
__________operator should be used. - The
__________operator is used to invert a boolean value, such as changing "Pressed" to "Not Pressed".
Show answers
&&||!
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.)
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.