FiniteStateMachine
Finite state machines are used all over the place in Flowcode components to keep track of things.
They are a means to allow a fixed number of deterministic states which can simplify a program.
Here is a very basic example.
We want to control a robot via a serial data connection. We control it by sending packets of 2 bytes.
The first byte is the value 'L' to signify the Left motor speed, the next byte is the motor speed 0-255.
The first byte is the value 'R' to signify the Right motor speed, the next byte is the motor speed 0-255.
The firmware for the robot could look something like this.
we always start at state 0, and we keep receiving bytes until the characters 'L' or 'R' are received. Once we receive one of the characters we know the next byte will be the corresponding motor speed so we can jump to the right state to collect and assign the value.
This would allow some fault tolerance. e.g. if the robot received a speed byte first then it would do nothing until the 'L' or 'R' bytes are received.
You could even control the Left motor without touching the Right motor by sending the 2 bytes packet starting with 'L' over and over again.
You could then expand the state machine if you wanted to by using a 3-byte packet and including the motor direction.
The first byte is the value 'L' to signify the Left motor speed, the next byte is the motor speed 0-255, the next byte is the direction 0-1.
The first byte is the value 'R' to signify the Right motor speed, the next byte is the motor speed 0-255, the next byte is the direction 0-1.
Of course state machine don't just apply to comms, you could do a similar thing with a switch press and a torch.
Start State 0 - Torch Off
Press 1 the torch turns on - State 1.
Press 2 the torch automatically flashes - State 2.
Press 3 the torch turns off - State 0.