Code Architecture: Command-Based vs. State Machines

Stop writing spaghetti code. How to organize complex subsystems using Finite State Machines.

Code Architecture: Command-Based vs. State Machines

In rookie code, everything is in one giant loop() function. if (buttonA) { intake.power(1); } This works for pushbots. It fails for champions.

The Finite State Machine (FSM)

Define “States” for your subsystems using Java Enums.

Example: Intake System

  • IDLE: Motor off. Arm up.
  • INTAKING: Motor on. Arm down.
  • TRANSFER: Motor reverse. Arm up. Indexer open.
  • JAMMED: Current spike detected. Pulse motor.

The Logic

Your loop simply checks: if (state == INTAKING) { doIntakeThings(); } Transitions happen based on sensors or timers.

Command-Based (FTCLib)

This is a library structure (borrowed from FRC) where “Commands” are objects.

  • new IntakeCommand(intakeSubsystem).schedule(); It handles the scheduling and concurrency for you.

Conclusion

For most FTC teams, State Machines are the sweet spot. They are easy to write, easy to debug, and powerful enough to automate complex actions like “Intake -> Transfer -> Ready to Fire”.

Explore FIRST® Robotics

FIRST® (For Inspiration and Recognition of Science and Technology) is a global robotics community preparing young people for the future. Discover the ultimate sport for the mind and see how you can get involved in STEM and robotics!

Learn More at firstinspires.org