I'm writing practice finite state machine code and can't wrap my head around the order of my "Switch" and "if" statements (which should come first).
Currently, I have it written as such:
task main()
{
// State variable default.
SystemStateType SystemState = State1;
While(1)
{
//Taken in from external sensors in real time
int reading;
if (reading == 0)
{
SystemState = State1;
}
else
{
SystemState = State2;
}
switch (SystemState)
{
case State1:
//actions
break;
case State2:
//other actions
break;
}
}
}
The code is intended to take sensor data in real time and respond accordingly. I realize that this is not actual functioning code, but I'm hoping that since the question is theoretical that my current code shown will suffice. Please let me know if I am missing anything.
Thank you!
Your
switchstatement examines the value of theSystemStatevariable, which is set through yourifstatement. So the correct order is to have yourifstatement, so that SystemStatevariable takes the desired value, and then examine the value of SystemStatein yourswitchstatement.Suppose that you had
ifandswitchstatements the opposite way, like this :Then, in the
switchstatement yourSystemStatevariable would always beState1.Of course, keep in mind that in the way you have written your code right now,
readingcannot receive any input. You need to givereadinga way to get a value.