Calculate the UART Baud Rate register for PIC devices

How do I calculate the UART configuration register values for a PIC 24F device, based on a desired Baud rate?

Currently the UART module has 2 values that affect the Baud rate, BRG (16-bit register) and BRGH (1-bit flag). How do I calculate these at runtime on the PIC instead of having to do it each time manually using Calc?

I've attempted to write the code based on the link to the datasheet given. Please review it.

// clock speed is 20 Mhz
#define FCY = 20000000

// baudRate - desired baud rate specified in bits per second
void CalcUARTBaudRate(unsigned int baudRate){

// the max baud rate with BRGH=0 is FCY/16
if (baudRate > (FCY / 16)){

// calc BRG with high baud rate (BRGH = 1)
U1MODEbits.BRGH = 1;
BRG = ((FCY / baudRate) / 4) - 1;
}else{

// calc BRG with low baud rate (BRGH = 0)
U1MODEbits.BRGH = 0;
BRG = ((FCY / baudRate) / 16) - 1;
}

}

• For this, and every question like it, read the datasheet. It's explained in great detail with a step-by-step example calculation. – Dan Laks Dec 17 '14 at 6:54
• re your code, I doubt the CLOCK_SPEED is correct.. – m.Alin Dec 17 '14 at 10:30
• @m.Alin - Yes, CLOCK_SPEED was not used by the code anyways. – Robinicks Dec 17 '14 at 12:33
• Why are you calculating baud rate in your firmware?? Work in something not so opaque, like a spreadsheet, until you understand what you're doing, THEN try in in silico and see if it works. – Scott Seidman Dec 17 '14 at 14:06