Page 398 - Programming Microcontrollers in C
P. 398
Input/Output Functions 383
The choice for bit rate for this system is 38.4 kbits per second. To
achieve this rate, the baud rate divisor value is given by
BR= E /16 BaudRate
clk
The E clock for the system is 8 MHz. Therefore, the divisor, BR, is
52 when rounded to the nearest integer value.
The register SC0BDL is defined in the header file hc12.h as a
type Register, or a collection of eight individual bits. In this case,
it is more understandable to put the data into this register as a char
rather than as a set of bits. The type of this location can be changed
to a type BYTE easily, using the line of code
#define BAUDREG *(BYTE *)&SC0BDL
Read this line of code from right to left. It says to cast a pointer to the
memory location SC0BDL onto a pointer to a type BYTE and then
dereference it. Therefore, whenever the defined name BAUDREG is
used, it accesses the BYTE contents found at the address SC0BDL.
This address is defined in the header file hc12.h.
The next two lines of code turn the bits TE and RE in SC0CR2
on. When these bits are ON, both the UART transmitter and receiver
will work.
The next function is putchar(). This routine sends the
designated BYTE to the serial port. It is necessary to wait until any
data in the transmit data register has been completely processed before
sending new data to this register. The first line of code does not allow
the value of SC0DRL to be altered until the transmit data ready bit,
TDRE, is set. Then the value x is stored in the location SC0DRL,
which causes the data to be sent to the serial port.
void putchar(BYTE x)
{
while(!SC0SR1.TDRE)
; /* wait until register is ready */
SC0DRL=x; /* send the data out */
}
The last of the I/O functions is getchar(). The getchar()
function is a little longer than the putchar() function. This difference
is caused by the fact that when a character is read in from the serial
port it should be immediately echoed back. Therefore, the entered