I spent a little time yesterday reworking my code for PenguinBot to replace the homemade state machine of If/then/else and switch statements, with a proper State Machine Library.
I specifically chose the SMLib State Machine Library because of it's simplicity and lack of overhead. I know there are other full featured State Machine Libraries out there, but this one serves the purpose well.
After all.. it's just a penguin that avoids obstacles... most of the time... more or less...
This library allows you to have a Head and Body for each state.
The "Head" is for initializing variables each time you transition into the state. The "Body" contains the actions that are to take place each time you loop through the state,such as incrementing a counter, or checking a sensor.
Regardless of whether you are in "Manual Mode", "Object Avoidance Mode", or the yet to be implemented "Light Following Mode", State Machine "m1" controls motion.
The states are as follows:
1 = Stopped2 = Forward3 = Avoiding Obstacle4 = Turn Left5 = Turn Right6 = ReverseThe Global Variable "MotionStop" dictates how much time is spend in any state.
Current (imperfect) code here:
Setup and Initialization of the State Machine :
This is the FSM.ino module:
MotionStop duration is typically set either as a Serial Command parameter when in Manual Mode, or predetermined time lapse for "In Motion" or "Idle" when in Autonomous Mode (Either Obstacle Avoidance or Light Following).
The exception to this, is in State 3 --- Avoid Obstacle. In this state, it has been determined that an obstacle blocks the way ahead, and an assessment is done as to whether there is more room to the left or to the right. "MotionStop" duration is set up to allow just enough time to turn the bot roughly 90 degrees. "MotionStop = 200; // Set turn time for Obstacle Avoidance"
Over the next few days, I will convert the rest of the code to use this library, and show the "Light Following Mode"
Arduino-Pi: Of Finite State Machines and Robotics
Arduino Playground: A novel and relaxed view on finite state machines
Robot Virtual Worlds – Maze Crawler
Embedded Micro: basic FSM to control a very simple robot.