Electronic – Best practice to keep main() in embedded systems

cembeddedstate-machines

I would like to know one thing about keeping the main() in embedded coding practice.
I have a stand-alone system that have n number of states and it would be shifting to the respective states.

At first I did a while(1) condition in main() and checked for any of the states to occur:

main()
{
  initialize;

  while(1)
  {
    check for state n.

    if state n found

    GoTo state n
  }
}

I don't know whether I made a mistake by defining the state n inside the main itself. Or should I separate the state n definition by separating it from main() and calling the state n function from main()?

I want to practice the best coding standard. What is the best practised method in embedded systems to keep the main()?

I would like to have inputs from your part to have the best structure for defining embedded coding methods to keep main() and corresponding source files.

What will be the case when the states become elaborate and complex? How should I keep the main()? I trust coding needs to be kept tidy.
I would appreciate your valuable inputs and suggestions.

Best Answer

If you're concerned that code for a simple switch() based state machine (SM) will become untidy, you can split it into smaller subroutines.

void do_state_s1() {
    // stuff
    if ( /* certain  contidition */ ) {
        g_iState = STATE_S2;  // transition to another state
    }
}

void do_state_s2()  {
    // other stuff
    if ( /* some other condition */ ) {
        g_iState = STATE_S1;
    }
}

void do_state_machine() {
    switch (g_iState) {
    case STATE_S1:
        do_state_s1();
        break;

    case STATE_S2:
        do_state_s2();
        break;
    };
}

void main() {
    g_iState = STATE_S1;        // initialize the SM

    while (1) {
        do_state_machine();
    }
}