jonblack / arduino-fsm

Arduino library for implementing a finite state machine.
MIT License
200 stars 97 forks source link

Fix init -- solution to initial state startup #7

Open PerfProf opened 8 years ago

PerfProf commented 8 years ago

This branch addresses an issue I had when using timed transitions. The initial state passed in to the Fsm constructor never called the on_enter function. There are ways to work around this behavior such as creating an additional state just for initialization. The same issue also applies to the classic Event driven FSM.

I chose to add a new boolean to determine if the FSM was freshly minted and to add a runtime test to call the on_enter function on the first call.

I've included an example to show the behavior and to verify that my change produces the correct results.

The change results in an increase of one byte of RAM for each FSM created and adds approximately 72 bytes of code.

This proposed change is for your consideration and the changed code is yours to do with as you please. There may be reasons of backward compatibility that precludes making this change or you may foresee design/performance issues too.

In my particular application I wanted to use a timed transition to interact with a hardware sensor. The on_enter method needs to set a hardware pin low to initiate a read trigger, then 20 mSec (or so) later, the on_exit function is called to collect the response from the sensor. Originally I had an IDLE loop that waited for 2 seconds before transitioning to the ReadSensor state and everything worked. Then I modified the design so that the initial state was to begin with reading the sensor followed by the IDLE state. I did some head scratching to figure out why my little sensor quit working. Perhaps it would beneficial to at least document the startup behavior to save others the confusion that plagued me.

Thanks for providing this small and well designed project.