Skip to main content

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

  1. The loop() method runs repeatedly at a frequency of approximately __________ times per second.
  2. If you put a long delay inside loop(), you risk losing connection to the __________ Station.
  3. The robot stops executing the loop() method once the driver presses the __________ button.
Show answers
  1. 50
  2. Driver Station
  3. Stop

Challenge

You need to create a simple diagnostic that shows the status of the "A" button on gamepad1 during the entire match.

Unit 2 simulator
Supports `init()`, `init_loop()`, `start()`, `loop()`, and `stop()`.
Reads `@TeleOp`, `@Autonomous`, `@Disabled`, telemetry, and `gamepad1`.
Handles local variables, simple math, `resetRuntime()`, and `getRuntime()`.
Does not execute hardware, `gamepad2`, `else` blocks, or loop structures.
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.