What is a finite state machine and when should I use one?
A Finite State Machine (FSM) is a state machine with a finite number of states that can be in one state at a time and transition to a different state when an event occurs . FSMs are often used in programming to enable more complex series of actions, especially when multiple tasks need to run concurrently and depend on each other's execution in a non-linear way .
FSMs are the appropriate tool when a robot needs to perform multiple tasks simultaneously, such as having automation in teleop while still allowing control over the drivetrain . This approach helps avoid issues that arise when teleop executes in a loop and servo logic includes sleep commands . Instead, FSMs allow for asynchronous code execution, where tasks are performed concurrently, and each task's state is checked without halting other tasks .
An example of a useful application is automating a scoring lift and dumper servo in teleop, where the robot extends a lift, angles a servo, waits, resets the servo, and retracts the lift, all while the driver can still control the drivetrain . This asynchronous pattern, where code repeatedly checks for state transitions in a loop() function, prevents the code from blocking other operations like drivetrain control .
It is not advisable to implement FSMs in a linear fashion for autonomous programs using a large switch statement, as this offers no significant benefit over simply using functions and can make debugging more difficult . Such "naive" implementations often struggle to react to stop requests because the code executes linearly .