Page 439 - Programming Microcontrollers in C
P. 439
424 Chapter 8 MCORE, A RISC Machine A Clock Program
Let us now look at output_time(). For this program, we will
send the time to the serial port to be displayed on a terminal. All of
the parameters hours, minutes, and seconds each have a range of 0 or
1 to some maximum two-digit value. Therefore, these numbers will
contain only tens and units. There will be no hundreds or thousands
or fractions, or minus signs for that matter. To convert these values to
characters to be sent to a function like putchar(), we have to do
two things. First count the number of tens, convert this number to an
ASCII digit and use it as an argument to putchar(). Then calculate
the number of units in the number, convert it to an ASCII digit and
send it to putchar(). These two operations are relatively easy to
program. In fact, these little functions can be written as function-like
macros easily, as follows:
#define hi(x) ((x)/10+’0’)
#define lo(x) ((x)%10+’0’)
Remember, the value passed to these two macro functions must lie
between 0 and 99. The first function hi(x) determines the number
of tens in the number and converts the result to an ASCII digit by
adding the character zero to the result. The second calculates the
number of units in the number by calculating the number modulo 10.
This value is converted to an ASCII digit when the character zero is
added.
With these two little macros in hand, the output_time()
function is easy to write:
void output_time(void)
{
putchar(‘\r’);
putchar(hi(hours));
putchar(lo(hours));
putchar(‘:’);
putchar(hi(minutes));
putchar(lo(minutes));
putchar(‘:’);
putchar(hi(seconds));
putchar(lo(seconds));
}
The output_time() function consists of a series of
putchar() function calls. The first has an argument ‘\r’. This
command causes the cursor on the screen to be returned to its leftmost