Each time we perform an exercise we will create functions which do things for us. In this case I now have a function which can be used to get the state of a user input. It will return (after a short interval) with the "proper" state of the input.
On the right we have the example code for a fully working torch with a debounced switch. The code is similar to our previous example, but we now call the key function to "debounce" the inputs each time. If you run exercise 2.4 you should find that the torch operation is now quite solid.
You will find the key function appearing in other programs which need to read the state of an input key.
/* Debounced Light Switch */
/* David Miles 2006 */
unsigned char key ( void )
{
unsigned char count=0;
unsigned char oldv, newv ;
oldv = PORTB & 1 ;
while ( count>20 )
{
newv = PORTB & 1 ;
if ( oldv==newv )
{
count++ ;
}
else
{
count=0 ;
oldv=newv ;
}
}
return oldv ;
}
void main ( void )
{
/* set all PORTB for input */
TRISB = 0xff;
/* PORTA bit 0 as output */
TRISA = 0x1e ;
/* repeat forever */
while (1)
{
/* wait for the button to */
/* go down */
while (key()==0);
/* if light on turn off */
if (PORTA & 1)
{
PORTA = 0 ;
}
else
{
/* if light off turn on */
PORTA = 0 ;
}
/* wait for the button */
/* to go up again */
while (key()==1);
}
}