1.3 Firmware Implementation

One of the most common ways to implement a state machine is through a firmware or software-based approach. In a firmware-based implementation, the state of the machine is typically implemented as software variables, and the state transitions and outputs are determined by writing code to implement the logic. The state time is usually determined by a software-based counter, which is usually derived from an underlying hardware timer. Figure 1-7 shows code snippet of a typical state machine implemented in firmware.

While the firmware-based solution is easy to implement, it takes up valuable CPU resources to process the state machine. In addition, the firmware-based solution is not power friendly since the CPU cannot be put to sleep.

Figure 1-7. Firmware-based State Machine Example
void stateMachine()
{
	while(1)
	{
		if(state_time == 0)
		{
			// Reload timer for state time
			state_time = RELOAD_VAL;

			// Current States and Outputs
			switch(current_state)
			{
				case STATE_INIT:				 // Current state
					stateInitializeTasks();		// Output function
					next_state = STATE_EXECUTE;	  // Direct state transition
					break;

				case STATE_EXECUTE:			    // Current state
					stateExecuteTasks();		   // Output function
					if(execution_complete)		 // Conditional state transition
						next_state = STATE_END;
					else
						next_state = current_state;
					break;

				case STATE_END:				  // Current state
					stateEndTasks();		 	// Output function
					next_state = STATE_INIT;	      // Direct state transition
					break;

				default:
					nextState = currentState;
					break;
			}

			// State Transitions (Next-state Functions)
			currentState = nextState;

			// Change software counter for state time
			state_time--;
		}
	}
}