PIC 16F1509 UART

PIC UART Serial port: I tested this on a PIC16F1509 with UART or EUSART as the datasheet likes to call it.

Calculating Baud rate

CLOCK / (16*(baud +1));

e.g MIDI at 31250, 8MHz internal clock
8000000 / (16 * 31251) = 15.999
The recommended SPBRG is 15. I don’t know why it’s not rounded up, I downloaded a calculator program and it says 15!

Note this is with the code below and the BRGH high speed flag set to 1. And an internal oscillator of 8MHz

Examples
9600: 51
14400: 34
19200: 25

Setting up

The below snippets of code are routines that need to be placed inside your PIC project. You can’t use both polled and interrupt (ISR).
Call the Setup_UART at the top of the main void function
all the other functions need to be outside of it, unless your polling then it needs to be inside the while(1) {} loop

 
Setup function

This will setup the PIC UART Serial port on your chip

void Setup_UART(){
SPBRG = 15; // Set The Baud Rate To Be 31250 bps

//in TXSTA register
BRGH = 1; // Set For High-Speed Baud Rate
SYNC = 0;
TXEN = 1;

//In RCSTA register
SPEN = 1;
CREN = 1;

TRISB5 = 1;
TRISB7 = 1;

//Note below – – you don’t need these unless you wish to use interrupts and write an ISR
RCIE = 1; // UART Receiving Interrupt Enable Bit
PEIE = 1; // Peripherals Interrupt Enable Bit
GIE = 1; // Global Interrupt Enable Bit
}

Interrupt receive

ISR code to receive (works on the new version of XC8 compiler)

void __interrupt() ISR(void)
{
  if (RCIF == 1) {
  unsigned char incoming = RCREG;  //Data is in here now..
  }
}

Polled Receive

Just run the following in a loop, just the same as the ISR above but just keeps checking for data in the register

if(RCIF == 1){
unsigned char incoming = RCREG;
}

Sending Data

void UART_Write(unsigned char data)
{
while(!TRMT); //Wait for register to be empty
TXREG = data; //Send data
return;
}

Things to note

unsigned char is an 8 bit value between 0 and 255
You can choose your variable or declare it at the beginning.