Chapter 9- Asynchronous Communication

advertisement
Chapter 9
Asynchronous Communication
Using the UART module
Simplified UART block diagram
figure 19-1 (DS61143)
Di Jasio - Programming 32-bit Microcontrollers in C
Baud Rate setting
In our case this translates to the following expression:
U2BREG = (36,000,000 / 4 / 115,200) -1 = 77.125
To decide how to best round out the result, use the reverse formula to calculate the
actual baud-rate and determine the percentage error:
Error = ((Fpb / 4 / (U2BREG + 1)) – baud rate) / baud rate %
With a value of 77 -> 115,384 Baud with an error of just 0.2%,
With a value of 78 -> 113,924 baud, 1.1% error,
Both are within the acceptable tolerance range for a standard RS232 port (+/- 2%) .
We can therefore define the constant BRATE as:
#define BRATE
77
Di Jasio - Programming 32-bit Microcontrollers in C
// 115,200 Bd (BREGH=1)
UxMODE register
register 19-5 (DS61143)
Di Jasio - Programming 32-bit Microcontrollers in C
UxSTA register
register 19-6 (DS61143)
Di Jasio - Programming 32-bit Microcontrollers in C
Initializing UART2
#include <p32xxxx.h>
// I/O definitions for the Explorer16
#define CTS
_RF12
// Clear To Send, input
#define RTS
_RF13
// Request To Send, output
#define TRTS
TRISFbits.TRISF13
// Tris control for RTS pin
void initU2(
{
U2BRG =
U2MODE =
U2STA =
TRTS
=
RTS
=
} // initU2
void)
BRATE;
U_ENABLE;
U_TX;
0;
1;
Di Jasio - Programming 32-bit Microcontrollers in C
//
//
//
//
//
initialize the baud rate generator
initialize the UART module
enable the Transmitter
make RTS an output pin
set RTS default status (not ready)
Sending and Receiving Data
int putU2( int c)
{
while ( CTS);
while ( U2STAbits.UTXBF);
U2TXREG = c;
return c;
} // putU2
// wait for !CTS, clear to send
// wait while Tx buffer full
char getU2( void)
{
RTS = 0;
// assert Request To Send !RTS
while ( !U2STAbits.URXDA); // wait for a new char to arrive
RTS = 1;
return U2RXREG;
// read char from receive buffer
}// getU2
Di Jasio - Programming 32-bit Microcontrollers in C
HyperTerminal Setup
Di Jasio - Programming 32-bit Microcontrollers in C
Tips and Tricks
To re-direct the output stream of the standard C library (stdio.h)
functions such as printf() to a UART:
Define

the function: _mon_putc()
Note that a “weak” definition is already provided in the library to send the default
output stream (stdout) to UART2 (convenient for all Explorer16 users).
Similarly


define: _mon_getc()
A default “weak” version is already provided in the library as well, connecting
UART2 receiver to the input stream (stdin).
Weak means that the compiler won’t complain when you define a new function
with the same name, it will simply replace it with the new one you provide.
NOTE
You are responsible for the UART initialization!
Before the first call to any stdio function (printf()…) make sure
the UART2 is enabled and the baud rate is set correctly.
Di Jasio - Programming 32-bit Microcontrollers in C
Download