Skip to main content

State Machines

Easydifficulty

A good PID controller won't rescue an arm routine that is half sleep() calls and half stale boolean flags. Robot code usually breaks in boring ways long before it breaks in interesting ones, and a state machine is the first tool for giving robot behavior a clear shape.

The boolean-flag scorer​

A scoring subsystem often starts out tidy:

FTCThe innocent beginning
boolean isIntaking = false;
boolean hasSample = false;
boolean isLifting = false;
boolean isScoring = false;

Then the robot gets more capable. The driver wants a cancel button. The intake gets a beam-break sensor. The arm needs time to move, and the claw should only open once the arm is at the top. Now there are a lot of flags, and nothing stops them from disagreeing. What does this mean?

FTCContradictory subsystem state
isIntaking = true;
hasSample = true;
isLifting = true;
isScoring = false;

Maybe the lift started moving while the intake was still pulling a piece in. Maybe a flag wasn't reset after the last cycle. Maybe the next if block is about to do something dangerous. The code can represent states the robot should never be in, and there's no single answer to "what is the subsystem doing right now?"

Try it​

In the demo, some driver requests only work from certain states. A request that isn't allowed from the current state isn't an error. It's just ignored, because no transition is defined for it.

Live demoA subsystem as a state machine
IDLEat rest
→
INTAKINGintake running
→
LOADEDsample secured
→
RAISINGarm moving up
→
SCORINGreleasing
↺ back to IDLE
Driver inputs
Sensor / automatic events
Transition log
Fire an event to begin…
Current state: IDLE · legal now: intake

That's what you get from a state machine: the set of things the robot is allowed to be doing gets smaller, and every one of them has a name.

States, events, and transitions​

A finite state machine has three parts:

SymbolMeaningScorer example
SSthe set of statesIDLE, INTAKING, LOADED, RAISING, SCORING
EEthe set of eventsdriver button, sample detected, arm at target
δ\deltathe transition functiongiven a state and an event, which state comes next

Written as a table, the scorer's transitions are:

Current stateEventNext state
IDLEdriver starts intakeINTAKING
INTAKINGsample detectedLOADED
INTAKINGdriver cancelsIDLE
LOADEDdriver requests scoreRAISING
RAISINGarm reaches targetSCORING
SCORINGrelease timer expiresIDLE

Any state and event pair that isn't in the table does nothing. That's deliberate, and it's where the safety comes from. The machine can't be INTAKING and RAISING at once, because state holds exactly one value.

If you like notation, the transition function is written δ:S×E⇀S\delta : S \times E \rightharpoonup S. The half arrow means the function is partial: most state and event pairs aren't defined, as in the table.

It also helps if the outputs depend only on the current state. INTAKING runs the intake, RAISING commands the arm target, IDLE holds everything still. When something looks wrong on the field, the state name on telemetry tells you exactly which block of code produced the motor commands. (A machine whose outputs depend only on the state is called a Moore machine.)

One enum, one transition gate​

This is the smallest version worth using. update() does one quick slice of work per loop, and enter() is the only place the state changes, so the state timer always resets along with it.

FTCA scorer: one state field, one transition gate
enum State { IDLE, RAISING, RELEASING }

private State state = State.IDLE;
private final ElapsedTime timeInState = new ElapsedTime();

// The one place state changes, so state-local time always resets with it.
private void enter(State next) {
state = next;
timeInState.reset();
}

public void requestScore() { // an outside event
if (state == State.IDLE) enter(State.RAISING);
}

// One slice of work. Never blocks.
public void update() {
switch (state) {
case IDLE:
lift.hold();
claw.close();
break;
case RAISING:
lift.setTarget(SCORE_HEIGHT);
if (lift.atTarget()) enter(State.RELEASING);
break;
case RELEASING:
claw.open();
if (timeInState.seconds() >= RELEASE_TIME) enter(State.IDLE);
break;
}
}

ElapsedTime is the FTC SDK's clock. You can read it at any moment without waiting, which is the opposite of what sleep() does.

ExerciseWhere the timer resets

enter() resets timeInState. Suppose you moved that reset to the top of update() instead. Trace three loops of RELEASING both ways.

Show solution

Resetting at the top of update() restarts the clock every loop, so timeInState.seconds() never gets past one loop period and RELEASING never ends. The claw stays open forever. The timer is supposed to mean "time since this state began," and the only moment that changes is inside enter(). Any variable that belongs to a state works the same way.

If you can trace the three legal transitions and see that no loop ever blocks, you have what you need for most subsystems. The rest of the lesson scales the same idea up to a whole autonomous routine.

Case study: an autonomous that can recover​

During the Power Play season, WolfPackMachina wrote their autonomous as a graph of scoring, pickup, recovery, and parking states. What makes it work isn't the number of boxes. Each box is a mode the robot can recover from, and each arrow is a condition the code can check during the loop.

WolfPackMachina Power Play adaptive autonomous state-machine diagram

Adaptive autonomous state graph. Diagram from WolfPackMachina's Power Play season autonomous architecture. Contact: jkc.cassidy+FTC@gmail.com.

How the machine is built​

It's still an enum, a switch, and a timer, but a real autonomous needs a few more things: actions that run once when a state starts, timed exits, checks for when a path is done, a way to recover when another robot pushes you, and subsystem updates that keep running every loop.

The code below is a simplified reconstruction of WolfPackMachina's Auto.java, not the whole file. Their original uses Paths.Path objects directly as states. This version uses a smaller set of named states so the structure is easier to follow. It shows the state table, the loop, the one method that changes state, and the three kinds of handler that keep coming up. There are nine handlers in total, and each one is a variation on one of those three, so writing them is left to you.

The state table: one field holds the mode​

One currentState field answers "what is the robot doing right now?" Everything else is bookkeeping for the handlers.

FTCAdaptiveAuto: the state table
enum State {
WAIT_FOR_PICKUP, // hold the scoring pose until settled
DISLODGE_CONE, // recovery: push a stuck cone free
ALIGN_LEFT_RAM, // contract, then line up on the stack
LEFT_RAM, // follow the pickup path
CONTESTED_LEFT_RAM, // recovery: we were pushed off-line
ALIGN_CONTESTED, // line up to score
ALIGN_PARK, // choose a park square, retract
PARK_CLOSE, // drive into the square
CYCLE_TRANSFER // hand off intake -> depositor
}

// The one authoritative field.
private State currentState = State.WAIT_FOR_PICKUP;

// Reset by the gate on every transition, never by a handler.
private final ElapsedTime timeInState = new ElapsedTime();
private final ElapsedTime timeSinceSettled = new ElapsedTime();
private boolean pathComplete, parking, contracting, robotSettled;

// Deliberately persistent ACROSS states: the cycle counter and the entry snapshot.
private ScoringState scoringState;
private double slidesPositionAtEntry;

There's no step counter, no sleep(), and no phase2b boolean.

The loop and the gate​

The loop never blocks. It runs the handler for the current state, then updates every subsystem and logs the mode no matter which state it's in. Only one method changes the state, so timers and flags always reset together.

FTCAdaptiveAuto: the loop
// Exactly one pass through. Never blocks.
public void loop() {
runHandlerFor(currentState);

// Then, regardless of which state we were in:
tickEverySubsystem();
log(currentState, scoringState, timeInState.seconds(), pathComplete);
}
FTCAdaptiveAuto: the transition gate
// The ONLY place currentState is written.
private void transitionTo(State next) {
// Re-entering a state is a no-op, except CYCLE_TRANSFER, which repeats.
if (next == currentState && next != State.CYCLE_TRANSFER) return;

currentState = next;
timeInState.reset();
timeSinceSettled.reset();
pathComplete = false;
parking = false;
robotSettled = false;
contracting = true;
}

public void requestPark() { // an outside event, same gate
if (currentState != State.ALIGN_PARK) transitionTo(State.ALIGN_PARK);
}
ExerciseWhy the flags reset in the gate

Every flag and timer resets in transitionTo() instead of in the handler that uses it. Add a tenth state on paper, once with the resets in the handler and once with them in the gate. How much did you have to remember each time?

Show solution

With resets in the handlers, every new state has to clear every flag that any other state might have left set. That's nine chances to forget one, and the resulting bug (say parking is still true, so the entry action never runs) only shows up on one particular path through the machine. With resets in the gate, a new state always starts clean and there's nothing to remember. It's the same reason the scorer had enter().

Three handler shapes​

Each of the nine handlers follows one of these three patterns.

FTCShape 1: an entry action, then a non-blocking wait
private void alignPark() {
if (!parking) { // true on the first loop in this state
chooseClosestParkSquare();
slides.retract();
parking = true; // ...and only the first loop
}
drive.holdStill();

if (timeInState.seconds() > PARK_SETTLE_TIME) { // poll; never sleep
transitionTo(State.PARK_CLOSE);
}
}
FTCShape 2: a precondition, refusing to act until safe
private void alignLeftRam() {
if (contracting && lift.aboveSafeHeight()) {
drive.holdPosition();
return; // do nothing this loop; try again next
}
contracting = false;
robot.contract();

boolean stillFollowing = follow(alignmentPath);
if (!stillFollowing) transitionTo(State.LEFT_RAM);
}
FTCShape 3: a branch, which is what makes it a policy
private void runLeftRam() {
if (pathProgress() > 0.05) slides.extend();

boolean stillFollowing = follow(pickupPath);
if (stillFollowing) return;

slides.retract();
if (wasPushedOffLine()) {
transitionTo(State.CONTESTED_LEFT_RAM); // recover, then come back
} else {
transitionTo(State.ALIGN_CONTESTED); // carry on as planned
}
resetPath();
}

And beneath all of it, every loop and in every state:

FTCThe per-loop subsystem tick
private void tickEverySubsystem() {
drive.tick();
intake.tick(); // and the intake runs its own state machine
depositor.tick(); // and so does the depositor
}

Small state machines running inside a bigger one is a common structure, usually called a hierarchical state machine. It's also why the subsystem tick runs in every state and not just the ones that move a mechanism.

Compare this with a script that calls one action after another. ALIGN_LEFT_RAM can refuse to move until the robot has pulled in. LEFT_RAM can branch to CONTESTED_LEFT_RAM if the robot gets pushed off its line. ALIGN_PARK picks its parking target once, on the first loop, instead of recalculating it every loop. The events that drive transitions are no longer just button presses. They're things like "path finished," "650 ms elapsed," "we got pushed," or "slides are below a safe height." A script can only run forward. A state machine can send the robot into recovery or parking when the match doesn't go to plan.

Habits that keep state machines working​

Never block the OpMode loop

sleep() and long while loops freeze the whole robot: driver control, sensor updates, telemetry, and every other subsystem. A state machine replaces "wait here" with "check whether it's done yet, this loop."

Telemetry should name the state

Print the current state and time in state every loop. "Stuck in RAISING for 2.4 seconds" tells you far more than four unrelated booleans.

Use state machines inside subsystems

State machines fit a single mechanism with a few clear modes: intake, shooter, lift, claw, endgame latch. When you need to coordinate many subsystems, Command-Based Programming sits on top of those subsystem machines.

Sources & references