Coroutines
A coroutine is a routine written as ordinary Java, read top to bottom, that can pause on a line and carry on from there. This lesson writes three for buttons, then one for autonomous.
- An
ArmandFlywheelwithisAtTarget(), from Conditions and Logging. - Tuned gains from PID Tuning in Tuner X.
- The simulator running, from Hardware Simulation.
The core calls
A coroutine body takes one argument, an object called coroutine. Four calls on it build every routine in this course.
// Start a command and keep going. It runs in the background until the routine ends.coroutine.fork(robot.arm.vertical()); // Pause here until a condition comes true.coroutine.waitUntil(() -> robot.arm.isAtTarget()); // Run a command and pause here until it finishes.coroutine.await(someStep); // Pause for a fixed time. Forked commands keep running through it.coroutine.wait(Seconds.of(1.0));vertical() is a runRepeatedly command, so it never finishes. If we used await on it, the routine would never get past that line. With fork, it runs in the background while the routine goes on to the next line. So fork anything that never ends, and await anything that can end.
waitUntil takes a lambda, () -> robot.arm.isAtTarget(), and calls it again on every loop to get a fresh answer. Without the () ->, the method would be called once, and that one answer would never change.
An arm routine
Hold Y and the arm goes up, waits until it gets there, comes back down, waits again, and prints that it is done. Here is the whole MyTeleop.java with it added. The marked lines are new.
package first.robot.opmode; import first.robot.Robot;import org.wpilib.command3.Command;import org.wpilib.command3.Coroutine;import org.wpilib.opmode.PeriodicOpMode;import org.wpilib.opmode.Teleop; @Teleop(name = "Teleop")public class MyTeleop extends PeriodicOpMode { private final Robot robot; public MyTeleop(Robot robot) { this.robot = robot; robot.driver.leftTrigger().whileTrue(robot.arm.vertical()); robot .driver .rightTrigger() .whileTrue(robot.flywheel.runFast()) .whileFalse(robot.flywheel.runSlow()); robot.driver.a().whileTrue(robot.flywheel.runFast()).whileFalse(robot.flywheel.stop()); // Y: raise the arm, wait for it, lower it, wait again. robot .driver .y() .whileTrue( Command.noRequirements(coroutine -> raiseAndLower(coroutine)).named("Raise And Lower")); } private void raiseAndLower(Coroutine coroutine) { coroutine.fork(robot.arm.vertical()); coroutine.waitUntil(() -> robot.arm.isAtTarget()); coroutine.fork(robot.arm.horizontal()); coroutine.waitUntil(() -> robot.arm.isAtTarget()); System.out.println("Raise And Lower: done"); }}private final Robot robot;andthis.robot = robot;keep the robot in a field. The routine is a method of its own, and the constructor'srobotparameter does not reach it.robot.driver.y().whileTrue(...)runs the routine while Y is held. Letting go cancels it, and everything it forked.Command.noRequirements(...)turns a coroutine into a command. Inside a mechanism you build commands withrunRepeatedly, which claims that mechanism. Outside a mechanism you useCommand.noRequirements. The routine claims nothing itself, and each command it forks claims its own mechanism for as long as it runs..named("Raise And Lower")is required.noRequirementshands back a builder, and it only becomes aCommandonce it has a name. The name is what the scheduler shows while it runs.raiseAndLoweris the routine itself. The scheduler hands it thecoroutineto callforkandwaitUntilon.System.out.printlnprints to the console: the VS Code terminal in simulation, the Driver Station console on the robot.
A flywheel routine
X spins the flywheel up, keeps it at speed for one second, then stops it. Add the binding under Y and the method under raiseAndLower.
import static org.wpilib.units.Units.Seconds; import first.robot.Robot;// ... the other imports, unchanged public class MyTeleop extends PeriodicOpMode { // ... fields, unchanged public MyTeleop(Robot robot) { // ... everything up to Y, unchanged // X: spin up, keep the speed for one second, stop. robot .driver .x() .whileTrue( Command.noRequirements(coroutine -> spinUpAndStop(coroutine)).named("Spin Up And Stop")) .whileFalse(robot.flywheel.stop()); } // ... raiseAndLower, unchanged private void spinUpAndStop(Coroutine coroutine) { coroutine.fork(robot.flywheel.runFast()); coroutine.waitUntil(() -> robot.flywheel.isAtTarget()); coroutine.wait(Seconds.of(1.0)); // stop() replaces runFast() and sends its zero before the routine ends. coroutine.fork(robot.flywheel.stop()); System.out.println("Spin Up And Stop: done"); }}Unlike the arm, the flywheel needs stop() at the end. Ending a routine cancels what it forked, and canceling is not stopping: the wheel would keep spinning. whileFalse covers the other way out, letting go of X early.
A routine in a loop
A routine is ordinary Java, so anything Java can do, it can do. B puts the arm routine inside a for loop and runs it three times.
public class MyTeleop extends PeriodicOpMode { // ... fields, unchanged public MyTeleop(Robot robot) { // ... everything up to X, unchanged // B: raise and lower the arm three times. robot.driver.b().whileTrue(Command.noRequirements(coroutine -> wave(coroutine)).named("Wave")); } // ... raiseAndLower and spinUpAndStop, unchanged private void wave(Coroutine coroutine) { for (int i = 0; i < 3; i++) { coroutine.fork(robot.arm.vertical()); coroutine.waitUntil(() -> robot.arm.isAtTarget()); coroutine.fork(robot.arm.horizontal()); coroutine.waitUntil(() -> robot.arm.isAtTarget()); } System.out.println("Wave: done"); }}The autonomous version
Autonomous has no button and nobody to let go of one. A wait that never comes true would eat the whole period. So every wait gets a time limit and somewhere to go when it runs out. This routine uses both mechanisms: raise the arm, spin up, shoot.
The diff adds one file: src/main/java/first/robot/opmode/RaiseAndShootOpMode.java. Four steps.
Step 1: The empty shell
package first.robot.opmode; import first.robot.Robot;import org.wpilib.command3.Command;import org.wpilib.command3.Coroutine;import org.wpilib.command3.Scheduler;import org.wpilib.opmode.Autonomous;import org.wpilib.opmode.PeriodicOpMode; @Autonomous(name = "Raise And Shoot")public class RaiseAndShootOpMode extends PeriodicOpMode { private final Robot robot; private final Command routine; public RaiseAndShootOpMode(Robot robot) { this.robot = robot; routine = Command.noRequirements(coroutine -> raiseAndShoot(coroutine)).named("Raise And Shoot"); } private void raiseAndShoot(Coroutine coroutine) { // Steps 2 to 4 go in here. } /** No trigger owns this routine, so the OpMode starts and stops it. */ @Override public void start() { Scheduler.getDefault().schedule(routine); } @Override public void end() { Scheduler.getDefault().cancel(routine); }}Paste the whole shell. No button binds this routine, so start() and end() schedule and cancel it.
Step 2: Fork the arm
// fork, not await: vertical() uses runRepeatedly and never finishes.coroutine.fork(robot.arm.vertical());Step 3: Wait, with a limit
Add import static org.wpilib.units.Units.Seconds; first. Every build runs Spotless, which strips an import no line uses yet, so add it again if it vanishes.
Coroutine.WaitResult armResult = coroutine.waitUntil(() -> robot.arm.isAtTarget(), Seconds.of(3.0));if (armResult.timedOut()) { // The flywheel never started, so there is nothing to stop. return;}This is the arm routine's wait with a limit added. waitUntil returns a WaitResult, kept here in armResult, and .timedOut() tells you which ending you got. Ignore it and the routine carries on as if the arm had arrived.
Step 4: The flywheel, then the shot
// vertical() is still running. That is the point of fork.coroutine.fork(robot.flywheel.runFast()); Coroutine.WaitResult flywheelResult = coroutine.waitUntil(() -> robot.flywheel.isAtTarget(), Seconds.of(3.0));if (flywheelResult.timedOut()) { coroutine.fork(robot.flywheel.stop()); return;} coroutine.wait(Seconds.of(1.0)); // shoot // stop() replaces runFast() and sends its zero on this loop, before the routine ends.coroutine.fork(robot.flywheel.stop());There is no feeder, so the one-second wait stands in for the shot. Every way out from here forks stop() first, for the same reason as the X button.
The finished body, and what it does over time:
private void raiseAndShoot(Coroutine coroutine) { // fork, not await: vertical() uses runRepeatedly and never finishes. coroutine.fork(robot.arm.vertical()); Coroutine.WaitResult armResult = coroutine.waitUntil(() -> robot.arm.isAtTarget(), Seconds.of(3.0)); if (armResult.timedOut()) { // The flywheel never started, so there is nothing to stop. return; } // vertical() is still running. That is the point of fork. coroutine.fork(robot.flywheel.runFast()); Coroutine.WaitResult flywheelResult = coroutine.waitUntil(() -> robot.flywheel.isAtTarget(), Seconds.of(3.0)); if (flywheelResult.timedOut()) { coroutine.fork(robot.flywheel.stop()); return; } coroutine.wait(Seconds.of(1.0)); // shoot // stop() replaces runFast() and sends its zero on this loop, before the routine ends. coroutine.fork(robot.flywheel.stop());}House rules
- A routine is
Command.noRequirements(coroutine -> body(coroutine))with.named(...). The body is a private method, so areturnplainly leaves the routine. - Wait on a condition with
coroutine.waitUntil(...)and a lambda. - Every wait in an autonomous has a time limit.
- Every exit stops the flywheel once it has started. The arm needs no stop, because its last position request holds it.
Check your work
- Start WPILib: Hardware Sim Robot Code, enable Teleoperated, and hold Y until it prints. Then X, then B.
- Switch to Autonomous and pick Raise And Shoot. That name is the
@Autonomousstring, not the class name. - Change the arm's tolerance to
Degrees.of(0.001)and run the autonomous again. Put it back. - Change the first line of
raiseAndShoottocoroutine.await(robot.arm.vertical())and run again. Put theforkback.
You should see
- On Y, the arm going up, then down, then
Raise And Lower: donein the console. On X, the flywheel spinning up, holding a second, and stopping. On B, three waves. - In autonomous, the arm rising, the flywheel spinning up, and the routine ending a second later. The flywheel coasts down and the arm keeps holding vertical.
- With the tolerance broken, the routine giving up after three seconds and the flywheel never starting.
- With the arm awaited, the arm moving and nothing else.
Check yourself
Why does the routine call coroutine.fork(robot.arm.vertical()) instead of coroutine.await(robot.arm.vertical())?
The Y button waits on robot.arm.isAtTarget() with no time limit. Why does the autonomous version need one?
You write coroutine.waitUntil(() -> robot.arm.isAtTarget(), Seconds.of(3.0)); and ignore what it returns. The arm jams. What does the routine do?
Why does waitUntil take () -> robot.arm.isAtTarget() instead of robot.arm.isAtTarget()?
You delete the line coroutine.fork(robot.flywheel.stop()) from the X routine. What does the flywheel do after the routine ends?