I can use the display as above, but it is rather difficult. I have to remember to "refresh" the digits all the time my program is running, otherwise the user will notice them flicker or even disappear. If I was serious about working this way I would ensure that whenever I am waiting for a user input (for example in the key function we wrote earlier) I call the display refresh to keep it going.
What I would really like is an automatic way of calling a "display refresh" function every now and then.
The code on the right re-arranges the original so that the refresh is taken away from the drawing action. Each time the refresh function is called it will re-draw the segment pattern for one of the digits.
Note that I am using an array to hold the actual segments which are to be displayed on the LEDs, when I want to display a pattern I load it into the array and then let the refresh take care of the rest.
/* segment patterns for our LEDs */
unsigned char
segments [DISPLAY_SIZE] ;
The refresh function also updates the display of only one of the LEDs. It uses the variable led_counter to keep track of the LED it is to work on. If I want to update all of the LEDs I have to call the refresh function four times. If you run Exercise 4.3 you will see the same nice, solid display.
/* number of LEDs in our display*/
#define DISPLAY_SIZE 4
/* segment patterns for our LEDs */
unsigned char
segments[DISPLAY_SIZE];
/* counter used by our refresh */
unsigned char led_counter = 0 ;
/* each time refresh is called it*/
/* sets the display for a led and*/
/* moves on to the next */
void refresh ( void )
{
/* turn off all the LEDs */
PORTA = 0 ;
/* set segments for the led */
PORTB = segments [led_counter] ;
/* turn the led on */
PORTA = enable [led_counter ] ;
/* move on to the next led */
led_counter = led_counter + 1 ;
/* see if we fell off the end */
if ( led_counter==DISPLAY_SIZE )
{
led_counter = 0 ;
}
}
/* display just loads the pattern*/
/* into the segment. refresh will*/
/* read it later */
void display ( unsigned char digit,
unsigned char pos )
{
segments [pos] = patterns [digit];
}
void main ( void )
{
setup_hardware () ;
/* display the values */
display ( 0, 0 ) ;
display ( 1, 1 ) ;
display ( 2, 2 ) ;
display ( 3, 3 ) ;
while (1)
{
/* refresh the display */
refresh () ;
/* delay */
delay ( 10 ) ;
}
}