Our stopwatch is like our player piano, in that it will operate in a number of states. At present I can think of two, PAUSED and RUNNING. When it is in running mode we want our time to update and when we are in paused we don't.
By using a state variable we can switch the update on and off. If you look at the code on the right you can see how this is done. Note how I have used #define
to give the states names, and how the initial value of the state variable is set to PAUSED. This means that after a reset our stopwatch will not be running, but will be switched off.
Once we have the global state variable we can start and stop our background counter from foreground code which will read the buttons.
/* state values for our stopwatch */
#define RUNNING 0
#define PAUSED 1
/* stopwatch state value */
unsigned char state = PAUSED ;
/* TMR0 Overflow handler */
void tmrHandler( void )
{
refresh () ;
/* only update the clock if we */
/* are running */
if ( state == RUNNING )
{
divisor++ ;
if ( divisor == 20 )
{
/* update count every */
/* every 10th of a */
/* second */
count++ ;
divisor = 0 ;
}
}
}