I'm using the FiniteStateMachine library http://playground.arduino.cc/code/FiniteStateMachine#.Uy4kzvldWSo for a project.
In a nutshell, you instantiate a State class for each of your states and each instance has up to three funtcions (enter, update, exit) from which it can transition to another state. You can transition to a new state, but there's no functionality to return to the previous state without knowing where you came from.
I thought I could implement this by having a pointer called previousStatePtr which pointed to the previous State instance. When transitioning to a new state, instead of giving the new state as an argument, you would give it a pointer which had been set to the previous state. Perhaps something like this:
State powerOnState = State(powerOnEnter,powerOnUpdate,NULL); // Declare some State instances
State mainMenuState = State(mainMenuEnter,mainMenuUpdate,mainMenuExit);
State someState = State(someEnter,someUpdate,someExit);
FiniteStateMachine stateMachine = FiniteStateMachine(powerOnState);
void processStateMachine() { // Call this from loop() to update state machine.
stateMachine.update();
}
// Try to create a pointer which can point to a State instance
State * previousStatePtr = &powerOnState; // This compiles
// but this doesn't
State * previousStatePtr; // Create a pointer which points to a State object
previousStatePtr = &powerOnState; // Specify which object's address to point to.
//error: expected constructor, destructor, or type conversion before '=' token
Right now I have code like this further down
void powerOnEnter(){ // do something };
void powerOnUpdate(){
if ( digitalRead(11) ) stateMachine.transitionTo(someState);
else stateMachine.transitionTo(mainMenuState);
void mainMenuEnter(){ // do something};
void mainMenuUpdate{
if ( digitalRead(11) ) stateMachine.transitionTo(someState);
};
I'd love to be able to do this:
void someEnter(){ }
void someUpdate() {
if ( digitalRead(11) ) stateMachine.transitionTo(previosuStatePtr); // Go back to previous state without having to know what it was
}
void someExit(){ // This executes before we transition to the next state.
previousStatePtr = &someState;
}
As a completely separate issue, I'd love to be able to pass data between states rather than rely on globals, but C++ isn't a language I've used much.