20.5.1.2 Reception

Address Detect Reception

#include <xc.h>

//Clocking based on CPU @8MHz, UART1 clocked from 1/2 speed peripheral bus @4MHz
#define FUART 4000000
#define BAUDRATE 9600
//Baud rate calculation for fractional baud rate mode
#define BRGVAL (FUART/BAUDRATE)

#define RECEIVED_CHAR_SIZE 16
uint8_t receivedChar[RECEIVED_CHAR_SIZE];
uint8_t receivedCharCount=0;

int main(void) {

    //Configure I/O
    _U1RXR = 50;             //Assign RP50 (RD1) to UART1 RX input function
    _TRISD1 = 1;             //Set RC6 as input

    U1CONbits.MODE = 4;     // Asynchronous 9-bit UART with address detect
    U1CONbits.CLKSEL = 0;   // FPB/2 as Baud Clock source
    U1CONbits.STP = 0;      // 1 stop bit

    //Use fractional baud rate divider
    U1CONbits.CLKMOD = 1;   
    U1BRG = BRGVAL; // Baud Rate setting for 9600

    U1PAbits.P2 = 0x45;      // Write parameter 2 with Address to match
    U1PBbits.P3 = 0xFF;      // Write parameter 3 register with mask value

    U1STATbits.RXWM = 0;     // Interrupt when there is one word or more in the buffer
    IEC3bits.U1RXIE = 1;     // Enable Receive interrupt

    U1CONbits.ON = 1;        // Enable UART
    U1CONbits.RXEN = 1;      // Enable UART RX.
    
    while(1) {}
    
    return 0;
}

void __attribute__((interrupt)) _U1RXInterrupt(void)
    { 
    IFS3bits.U1RXIF = 0;     // Clear RX interrupt flag
    while(U1STATbits.RXBE == 0) // Check if RX buffer has data to read 
    { 
        receivedChar[receivedCharCount++] = U1RXB; // Read a character from RX buffer
        
        //Wrap around array index when array is full
        if (receivedCharCount >= RECEIVED_CHAR_SIZE) {
            receivedCharCount = 0;
        }
    }
}