Lesson 2.3: Running Real-Time Robot Logic Inside loop()
Context
The loop() method controls the robot's performance during the match. Because it runs at a high frequency (approximately 50 times per second), it allows for smooth movement and rapid sensor polling. Efficiency in this method is critical, any "blocking" code (like a sleep command) will freeze the robot and could cause a communication timeout with the Driver Station.
The loop() Lifecycle
In an OpMode, the loop() method is executed repeatedly after the driver presses the "Play" button and until they press "Stop". It usually follows a sensing → thinking → acting cycle: it reads the latest values from the Gamepads or sensors, calculates the necessary power adjustments, and commands the Control Hub's motor controllers to update voltage outputs.
Since loop() is non-blocking, it is ideal for TeleOp where driver inputs are changing in real-time.
Annotated Code
@TeleOp(name="Loop_Demo")
public class LoopDemo extends OpMode {
@Override
public void init() {
telemetry.addData("Status", "Ready to Play");
}
@Override
public void loop() {
// This logic runs ~50x a second to check for driver input
double drivePower = -gamepad1.left_stick_y;
// Streaming hardware data back to the DS for real-time monitoring
telemetry.addData("Motor Command", drivePower);
telemetry.addData("Cycle Time", getRuntime());
}
}
Fill-in-the-Blank Practice
- The
loop()method runs repeatedly at a frequency of approximately__________times per second. - If you put a long delay inside
loop(), you risk losing connection to the__________Station. - The robot stops executing the
loop()method once the driver presses the__________button.
Show answers
- 50
- Driver Station
- Stop
Challenge
You need to create a simple diagnostic that shows the status of the "A" button on gamepad1 during the entire match.
Show answer
@Override
public void loop() {
telemetry.addData("Button A", gamepad1.a);
telemetry.update();
}
Ready to move on?
Sign in with Google to save your progress with Telemark, or continue without saving.