Lesson 5.1: Using if Statements to Decide When a Motor Should Run
Technical Context
The if statement is the fundamental mechanism for preventing unintended robot movement. By wrapping hardware commands in a conditional block, you ensure that voltage is only applied to I/O ports when specific criteria are met — such as a driver input or a sensor state. This prevents "runaway" robots and mechanical damage during the sensing-thinking-acting cycle.
How if Statements Turn Inputs into Actions
In the Java JVM, an if statement evaluates a boolean expression found within the parentheses. If the expression evaluates to true, the code block encapsulated by curly braces {} is executed. In FTC, this is typically used to poll the state of a gamepad button (e.g., gamepad1.a) or a digital sensor. Because the loop() method executes approximately 50 times per second, the if statement allows the robot to make real-time decisions based on the current state of the hardware registry.
Annotated Code
package org.firstinspires.ftc.teamcode.opmodes;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
@TeleOp(name="Basic_Logic_Test")
public class BasicLogic extends OpMode {
private DcMotor intake;
@Override
public void init() {
// Hardware instantiation via the HardwareMap
intake = hardwareMap.get(DcMotor.class, "intake");
}
@Override
public void loop() {
// Foundational if statement for hardware activation
if (gamepad1.a) {
// Command is only sent to the Control Hub if 'a' is true
intake.setPower(1.0);
}
// Technical note: Without an 'else', the motor will never stop
// once 'a' has been pressed.
}
}
Fill-in-the-Blank Practice
- A foundational decision-making structure in Java starts with the
__________keyword followed by a conditional expression in parentheses. - The code following a conditional statement should be encapsulated in
__________to prevent logic errors and ensure multiple statements execute together. - In a sensing-thinking-acting machine, the
ifstatement represents the__________phase of the cycle.
Show answers
if- curly braces
{} - thinking
Template Challenge
Robot Scenario: Your team needs a safety switch. The DC Motor named "flywheel" should only run at full power if the driver is holding gamepad1.right_bumper.
Show answer
@Override
public void loop() {
if (gamepad1.right_bumper) {
flywheel.setPower(1.0);
} else {
flywheel.setPower(0.0);
}
}
Ready to move on?
Sign in with Google to save your progress with Telemark, or continue without saving.