Linear vs Iterative OpModes
OpMode Types in FTC
FTC supports two main OpMode types: LinearOpMode and Iterative OpMode. Understanding the difference helps you choose the right structure for your code.
A LinearOpMode runs your code from top to bottom, like a script. An Iterative OpMode runs your code in a loop, giving you more control over timing and state.
See: gm0: OpMode Types
Key Differences
LinearOpMode vs Iterative OpMode:
- LinearOpMode: Code runs sequentially, like a script.
- Iterative OpMode: Code runs in repeated loop() calls.
- LinearOpMode: Easier for beginners and autonomous routines.
- Iterative OpMode: More control, better for advanced TeleOp.
LinearOpMode Example
@TeleOp(name = "LinearTeleOp")
public class LinearTeleOp extends LinearOpMode {
private DcMotor leftDrive, rightDrive;
@Override
public void runOpMode() {
leftDrive = hardwareMap.get(DcMotor.class, "left_drive");
rightDrive = hardwareMap.get(DcMotor.class, "right_drive");
waitForStart();
while (opModeIsActive()) {
double leftPower = -gamepad1.left_stick_y;
double rightPower = -gamepad1.right_stick_y;
leftDrive.setPower(leftPower);
rightDrive.setPower(rightPower);
telemetry.addData("Left Power", leftPower);
telemetry.addData("Right Power", rightPower);
telemetry.update();
}
}
}
Iterative OpMode Example
@TeleOp(name = "IterativeTeleOp")
public class IterativeTeleOp extends OpMode {
private DcMotor leftDrive, rightDrive;
@Override
public void init() {
leftDrive = hardwareMap.get(DcMotor.class, "left_drive");
rightDrive = hardwareMap.get(DcMotor.class, "right_drive");
}
@Override
public void loop() {
double leftPower = -gamepad1.left_stick_y;
double rightPower = -gamepad1.right_stick_y;
leftDrive.setPower(leftPower);
rightDrive.setPower(rightPower);
telemetry.addData("Left Power", leftPower);
telemetry.addData("Right Power", rightPower);
telemetry.update();
}
}
When to Use Each Type
Choose based on your needs:
- Use LinearOpMode for simple autonomous or TeleOp routines.
- Use Iterative OpMode for advanced TeleOp with state machines or timing.
- Start with LinearOpMode if you are new to FTC.
- Convert to Iterative OpMode as your code grows more complex.
Converting Between Types
You can convert a LinearOpMode to an Iterative OpMode by moving your logic into the loop() method and managing state with variables. For example, if you have a sequence of actions in LinearOpMode, you can use a state variable in Iterative OpMode to step through them.
Further Reading & Resources
Next Steps
Practice: OpMode Types
Try these to reinforce your understanding:
- Write a LinearOpMode that drives a motor.
- Convert it to an Iterative OpMode.
- Compare the structure and behavior of both types.