Close

Firmware -- State machine

A project log for Heartbeat Logger

A portable device that logs a snippet of your heart at the push of a button.

Ole Andreas UtstumoOle Andreas Utstumo 06/01/2016 at 11:430 Comments

The system operates using a simple state machine.

The states exist in the code as functions that are called over and over again:

void die(void);
void sampling(void);
void sleep(void);
void wake(void);
To easily manage the states, we create a function pointer that can point to the state's function:
void (*function_pointer)(void);

To set a new state, all we have to do is to make the function pointer point to another state's function (the & character can be omitted):

function_pointer = &wake;

The function pointer is called repeatedly in an everlasting while loop in main, so that it constantly executes the current state:

	while(1){
		function_pointer();
		
	}
The state is changed by certain conditions. Take the wake state for example:
void wake(void){
	
	GLED_on();
	afe_enable();
	sdcard_enable();
	ext_enable();
	tc_enable(&tc_sampler_instance);
	adc_enable(&adc_instance);
	
	if(sdcard_init()){

                function_pointer = sampling;

		buffer_counter = 0;
		timestamp = 0;
		buttoncounter = 0;	
		buffer_current = buffer_a;
		buffer_last = buffer_b;
		
		update_battery_voltage();

		tc_start_counter(&tc_sampler_instance);
		usart_write_buffer_job(&usart_instance, buffer_current, 2);
		
	}else
		function_pointer = die;
	
}

Here, the next state is set to either sampling or die, depending on the success of the SD card initialization, just as described in the state machine diagram at the top. When the program returns from the function call, the function pointer will be called again, but this time it is pointing to a different state -- et voila!

Discussions