2.3.2 How to Configure EUSART2
EUSART2 will be configured for 9600 baud rate and the standard 8-N-1 (eight data bits, no parity bit and one Stop bit) frame format.
Given the configured frequency and the desired baud rate of 9600, the 16-bit Baud Rate Generator (BRG16) must be used, and High Baud Rate (BRGH) must be enabled. The SPEN bit enables the Serial Port (EUSART) as a whole, while TXEN enables its transmitter.
/* Transmit Enable */
TX2STAbits.TXEN = 1;
/* High Baud Rate Select */
TX2STAbits.BRGH = 1;
/* 16-bit Baud Rate Generator is used */
BAUD2CONbits.BRG16 = 1;
/* Serial Port Enable */
RC2STAbits.SPEN = 1;
The value to be written in SP2BRG is found in the table below, taken from the device data sheet.
BAUD RATE | SYNC =
0 , BRGH = 1 , BRG16 =
1 or SYNC = 1 , BRG16 =
1 | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
FOSC = 8.000 MHz | FOSC = 4.000 MHz | FOSC = 3.6864 MHz | FOSC = 1.000 MHz | |||||||||
Actual Rate | % Error | SPBRG value (decimal) | Actual Rate | % Error | SPBRG value (decimal) | Actual Rate | % Error | SPBRG value (decimal) | Actual Rate | % Error | SPBRG value (decimal) | |
300 | 300.0 | 0.00 | 6666 | 300.0 | 0.01 | 3332 | 300.0 | 0.00 | 3071 | 300.1 | 0.04 | 832 |
1200 | 1200 | -0.02 | 1666 | 1200 | 0.04 | 832 | 1200 | 0.00 | 767 | 1202 | 0.16 | 207 |
2400 | 2401 | 0.04 | 832 | 2398 | 0.08 | 416 | 2400 | 0.00 | 383 | 2404 | 0.16 | 103 |
9600 | 9615 | 0.16 | 207 | 9615 | 0.16 | 103 | 9600 | 0.00 | 95 | 9615 | 0.16 | 25 |
10417 | 10417 | 0 | 191 | 10417 | 0.00 | 95 | 10473 | 0.53 | 87 | 10417 | 0.00 | 23 |
19.2k | 19.23k | 0.16 | 103 | 19.23k | 0.16 | 51 | 19.20k | 0.00 | 47 | 19.23k | 0.16 | 12 |
57.6k | 57.14k | -0.79 | 34 | 58.82k | 2.12 | 16 | 57.60k | 0.00 | 15 | — | — | — |
115.2k | 117.6k | 2.12 | 16 | 111.1k | -3.55 | 8 | 115.2k | 0.00 | 7 | — | — | — |
/* Baud rate 9600 */
SP2BRGL = 25;
SP2BRGH = 0;