Setup for UART Transmit
The following procedure is used to transmit a byte of data:
- Configure the clock input and baud rate as detailed in Clocking and Baud Rate Configuration.
- Configure the data width and parity by writing a selection to the MODE[3:0] bits.
- Configure the polarity, Stop bit duration and flow control.
- Configure the TX interrupt watermark using the TXWM[2:0] bits (UxSTAT[30:28]).
- Configure the address detect if needed as detailed in Address Detect.
- Set the ON bit (UxCON[15]).
- Set the TXEN bit (UxCON[5]).
- Write the data byte value to the UxTXB register.
A TX interrupt will be generated according to the TXWM[2:0] bits’ interrupt watermark setting. The TXWMx bits can be configured to generate a TX interrupt when the buffer has one to eight empty slots.
The UARTx Transmit Buffer (UxTXB) has two associated flags to indicate its contents. The TX Buffer Empty Status bit, TXBE (UxSTAT[21]), indicates that the buffer is empty, and the TX Buffer Full Status bit, TXBF (UxSTAT[20]), indicates that there are no empty slots in the buffer and it should not be written.
UART1 Transmission with Interrupts
#include<xc.h>
#define FUART 4000000
#define BAUDRATE 9600
#define BRGVAL (((FUART/BAUDRATE)/16)-1)
uint8_t TxChar[10] = {'1','2','3','4','5','6','7','8','9','0'};
uint8_t i=0;
int main(void) {
// Configure oscillator as needed
// Configure oscillator as needed
_RP23R = 9; // Assign U1TX to pin RP23
U1CONbits.MODE = 0; // Asynchronous 8-bit UART
U1CONbits.BRGS = 0; // Low-Speed Mode
U1CONbits.CLKSEL = 0; // FPB/2 as Baud Clock source
U1CONbits.STP = 0; // 1 stop bit
U1BRG = BRGVAL; // BRG setting for 9600 baud rate
U1STATbits.TXWM = 0; // Sets transmit interrupt when there are eight
// empty slots in the buffer
_U1TXIE = 1; // Enable Transmit interrupt
U1CONbits.ON = 1; // Enable UART
U1CONbits.TXEN = 1; // Enable UART TX. This generates TX interrupt.
while(1)
{
}
return 0 ;
}
void __attribute__((interrupt, no_auto_psv)) _U1TXInterrupt(void)
{
_U1TXIF = 0; // Clear TX interrupt flag
while((U1STATbits.TXBF == 0) && (i<10) )
{
U1TXB = TxChar[i++]; // Transmit one character
}
}