first time poster. I was pretty confident programming in C but C++ and it's classes are still a bit new to me.
I'm trying to build a class that acts as a statemachine. I want to be able to make multiple instances of it so i can have multiple statemachines running at the same time.
The states are functions that i would like to pass to that class and that will get executed with performState(). I've got an idea how it should work but I just can't get it to work.
#include <iostream>
// FROM HEADER FILE
typedefvoid (*PFNSTATEFUNCTION)(); // I prefer to use typedef
class StateMachine
{
public:
void setStateFunction(PFNSTATEFUNCTION fptr);
void performState();
StateMachine();
private:
PFNSTATEFUNCTION stateFunction;
};
// FROM CPP FILE
// ------------------------------------------------------------
// Member functions definitions including constructor
// ------------------------------------------------------------
StateMachine::StateMachine() : stateFunction(NULL) // use nullptr in C++11 code
{
//stateFunction = NULL; moved to init list
}
// ------------------------------------------------------------
// Set Function Pointer
// ------------------------------------------------------------
void StateMachine::setStateFunction(PFNSTATEFUNCTION fptr)
{
stateFunction = fptr;
}
// ------------------------------------------------------------
// Actual state machine - call this in your program
// ------------------------------------------------------------
void StateMachine::performState()
{
if( stateFunction != NULL )
{
//stateFunction();
(*stateFunction)(); // overkill, but reminds me it's a function pointer
}
}
//StateMachine myStateMachine1; moved into main()
void testFunction()
{
//ledState3 = LOW;
std::cout << "ledState3 = LOW\n";
}
int main()
{
StateMachine myStateMachine1; // prefer non-global
myStateMachine1.setStateFunction( testFunction ); // the & is optional in &testFunction
//while(1)
for(int i = 0; i < 3; ++i) // FOR TESTING
{
myStateMachine1.performState();
}
return 0;
}
it compiled in the end. I'm working for the first time with the Spark Development board and didn't realise all code needs to go in the void loop(void) section.
thank you andy westken for the syntax corrections ... i've taken it all on board for the future.