We now have an idea of how our device will work, at least at the state level. What we want next is a function which will implement this behaviour for us.
On the right is an empty function which implements the state diagram above. We have used the switch construction to allow us to select appropriate operation, both in terms of a set of behaviour depending on the state of the device, but also to select the action to be performed when a particular event occurs.
When we get an event we call the function to deal with it. Note how I have given printable values for the events and states. I have also used the DEBUG
technique so that I can turn on statements which will show the state of my system before and after I feed it an event. This will let me prove that it works (which is something I should always consider when I am writing the code).
/* values for the events */
#define DOT_EVENT '.'
#define DASH_EVENT '-'
#define SPACE_EVENT ' '
#define STUCK_EVENT '*'
/* values for the states */
#define BUSY_STATE 'B'
#define QUIET_STATE 'Q'
#define DEBUG
/* state variable - set at QUIET */
unsigned char morse_state =
QUIET_STATE ;
/* we call the function to deal */
/* with an event. How it behaves */
/* depends on the current state */
void do_morse (unsigned char event)
{
#ifdef DEBUG
lcd_print_ch ( event ) ;
lcd_print_ch ( morse_state ) ;
#endif
/* use a switch to select the */
/* code for the current state */
switch ( morse_state )
{
case BUSY_STATE :
/* now have a switch for each */
/* event which might happen */
/* in this busy state */
switch ( event )
{
case DOT_EVENT :
/* store the dot here */
break ;
case DASH_EVENT :
/* store the dash here */
break ;
case SPACE_EVENT :
/* work out the code */
/* and move to QUIET */
/* state */
morse_state = QUIET_STATE ;
break ;
case STUCK_EVENT :
/* go to quiet state */
morse_state = QUIET_STATE ;
}
/* now handle events in */
/* quiet state */
case QUIET_STATE :
switch ( event ) {
case DOT_EVENT :
/* store the dot here */
/* move to BUSY state */
morse_state = BUSY_STATE ;
break ;
case DASH_EVENT :
/* store the dash here */
/* move to BUSY state */
morse_state = BUSY_STATE ;
break ;
case SPACE_EVENT :
/* do nothing */
break ;
case STUCK_EVENT :
/* do nothing */
break ;
}
}
#ifdef DEBUG
lcd_print_ch ( morse_state ) ;
#endif
}