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
switch
statement examines the value of theSystemState
variable, which is set through yourif
statement. So the correct order is to have yourif
statement, so that SystemStatevariable takes the desired value, and then examine the value of SystemState
in yourswitch
statement.Suppose that you had
if
andswitch
statements the opposite way, like this :Then, in the
switch
statement yourSystemState
variable would always beState1
.Of course, keep in mind that in the way you have written your code right now,
reading
cannot receive any input. You need to givereading
a way to get a value.