The Body of a Command
Something Looks Familiar Here…
Section titled “Something Looks Familiar Here…”If you’ve ever coded in Scratch, with blocks, or taken an intro to programming class, you’ve probably written software as a sequence of statements. Like so:
int number = 1;while (number < 4) { System.out.println("-".repeat(number)); number = number + 1;}while (number > 0) { System.out.println("-".repeat(number)); number = number - 1;}(In case you were curious - this prints a triangle to the console.)
From the previous section, you might remember that command-based programming, as a whole, cannot be represented with just a sequence of statements. However, individual commands (or robot actions) can.
For instance, this command body runs a motor at full speed forever:
System.out.println("Full Speed Baby!");while (true) { motor.setThrottle(1.0); coroutine.yield(); // Confused? We'll explain this in the section below}And this command body would rotate your robot by roughly 90 degrees, then stop:
double targetDirection = getCurrentYaw() + 90;while (getCurrentYaw() < targetDirection) { differentialDrive.arcadeDrive(0, 0.5); coroutine.yield();}differentialDrive.arcadeDrive(0, 0);Fundamentally, the commands (or robot actions) themselves can be represented with familiar programming structures: while loops, variables, method calls, and more.
Notice that we said command body, not command! The command body defines the actions it executes after it is run. However, a command must also define requirements, priority, and more.
The Meaning of coroutine.yield();
Section titled “The Meaning of coroutine.yield();”coroutine.yield() is a special statement that must be called inside of while loops.
It allows for commands to run in parallel, while ensuring that background tasks
(like motor safety checks) are run.
An anology would be the
sips of water you take while you finish your homework.
The coroutine object contains many other useful methods that can only be called
inside of commands.
Some of these will be mentioned in the following sections.
Because coroutine.yield() can’t be called outside of commands, it is
highly discouraged to use while loops outside of commands.