-3
\$\begingroup\$

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;
    }

}
\$\endgroup\$
  • 8
    \$\begingroup\$ For this, and every question like it, read the datasheet. It's explained in great detail with a step-by-step example calculation. \$\endgroup\$ – Dan Laks Dec 17 '14 at 6:54
  • \$\begingroup\$ re your code, I doubt the CLOCK_SPEED is correct.. \$\endgroup\$ – m.Alin Dec 17 '14 at 10:30
  • \$\begingroup\$ @m.Alin - Yes, CLOCK_SPEED was not used by the code anyways. \$\endgroup\$ – Robinicks Dec 17 '14 at 12:33
  • \$\begingroup\$ 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. \$\endgroup\$ – Scott Seidman Dec 17 '14 at 14:06
4
\$\begingroup\$

From DS39708, "dsPIC33/PIC24 Family Reference Manual, UART", section 3.0, "UART BAUD RATE GENERATOR":

BGRH=0 BGRH=1

\$\endgroup\$
  • \$\begingroup\$ I'm not very good at math, can you show a code example of how this equation translates into code? \$\endgroup\$ – Robinicks Dec 17 '14 at 7:59
  • 1
    \$\begingroup\$ Do the maths the best you can and add it to the end of the question or add it as an answer. Then some one will check it. \$\endgroup\$ – Spoon Dec 17 '14 at 8:57
  • \$\begingroup\$ @Spoon - I did it. Can you check the code I posted for errors? \$\endgroup\$ – Robinicks Dec 17 '14 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.