SMILEY’S WORKSHOP ☺
from very complex to extremely complex. We’ll try to
keep it as simple as we can and only use the C switch
statement that we’ve seen before as our state machine in
a simple demonstration application nav_menu.c that you
can find under the avr_applications section of avrtoolbox.
You can use it as a template if you want to write a menu
system of your own. In this application, we will also show
how to enter text and numbers using the Navigator keys.
The nav_menu.c application builds on the tester code
shown above using a series of switch statements in
functions to keep track of the system state. The program
opens with the LCD showing the program name and
revision as shown in Figure 12.
First, we define the number of states: #define
MAX_TOP 5 — and don’t forget that since we are
counting from 0, that the maximum of five means that we
actually will have six functions named according to what
they do as follows:
Enter text
Enter number
View text
View number
Erase text
Erase number
When we run the code, the forever loop will either
increment or decrement a variable ‘top,’ depending on
our presses of the UP or DWN key:
if(key == UP)
{
if (top <= MAX_TOP) top++;
}
if(key == DWN)
{
if (top > 0) top—;
}
second line of the LCD:
delay(500);
lcd_set_cursor( 0, 1 );
lcd_puts(itoa(top,num,10) );
When the user pressed the center (CTR) button:
if(key == CTR)
{
get_top(top);
}
The get_top(top) function is called:
void get_top(uint8_t get)
{
switch (get)
{
case 0:
entr_txt();
break;
case 1:
entr_num();
break;
case 2:
view_txt();
break;
case 3:
view_num();
break;
case 4:
erse_txt();
break;
case 5:
erse_num();
break;
default:
break;
}
}
Suppose you press the up button four times to show
the number 3, and then press CTR. This will switch to case
3 which calls the view_num() function:
■ FIGURE 13. The view_num.
At the end of the loop, we wait
half a second to make sure the user
has pressed and released a key, then
we show the ‘top’ number on the
Theory is all well and
good, but to really learn this
stuff you have to get your
hands on some tangible items
that blink, whirr, and
sometimes detonate. As a
service for the readers of the
Smiley’s Workshop articles,
we have simple and
inexpensive projects kits
available that can help you
make it real. You can find
these kits (and some darn
good books) at the Nuts &
Volts Webstore.
February 2012 65