SMILEY’S WORKSHOP ☺
LISTING 1
#include
“c:\avrtoolbox\libavr\source\general\util\util.
h”
#include
“c:\avrtoolbox\libavr\source\driver\external_
hardware\
lcd_hd44780\lcd.h”
#include
“c:\avrtoolbox\libavr\source\driver\external_
hardware\
nav_button\nav.h”
int main( void )
{
uint8_t key = 0;
lcd_init();
nav_init();
lcd_puts(“NavButt”);
delay(500);
lcd_clear();
lcd_puts(“REV028”);
delay(1000);
lcd_clear();
for(;;)
{
if(nav_available())
{
key = nav_get_key();
if(key == CTR)
{
lcd_home();
lcd_blank(16);
lcd_puts(“CTR!”);
}
if(key == LFT)
{
lcd_home();
lcd_blank(16);
lcd_puts(“LFT!”);
}
if(key == RGT)
{
lcd_home();
lcd_blank(16);
lcd_puts(“RGT!”);
}
if(key == UP)
{
lcd_home();
lcd_blank(16);
lcd_puts(“UP!”);
}
if(key == DWN)
{
lcd_home();
lcd_blank(16);
lcd_puts(“DWN!”);
}
delay(100);
lcd_home();
lcd_blank(16);
}
}
}
buttons
uint8_t nav_available(); // true if a new button
press is available
uint8_t nav_get_button(); // return the next
available button
mapped to each of the five buttons. For example:
#define NAV_LFT_PORTX PORTD
#define NAV_LFT_DDR DDRD
#define NAV_LFT_PINX PIND
#define NAV_LFT_PIN PD6
Listing 1 makes for a very simple tester program. When
we press the down button, the LCD shows DWN! as
shown in Figure 10.
As usual, this simplicity is hiding some complexity
under the hood that we will look at in more detail. When
you first look at this — especially if
you are a novice — you might
correctly ask ‘Where is all the code
that notes when a button is pressed?’
Well, that is all set up by the
nav_init() routine that sets up an ISR
(Interrupt Service Routine) that runs
in the background, out of sight of our
main loop. A timer peripheral is set to
interrupt the main code every 5 mS
(milli-seconds or 0.005 seconds) and
check the state of the buttons. If a
button is low for five consecutive 5
mS intervals ( 25 mS), then we are
reasonably sure that the button has
been pressed. We will get into a lot of
detail about timers and ISRs in another
Workshop, but for now I recommend
that you look at the nav_init() function
to get a feel for what is going on.
There are several other neat tricks
hidden under the hood of this code,
including the way the port pins are
Here we see that we require four separate definitions
just for setting up the LFT button in the initiation. If you
want to wire the buttons to different ports and pins, you
will need to change them in these definitions in nav.h.
■ FIGURE 10. DWN!
February 2012 63