In the PIC archy, the baud rate register needs a value equal to Fosc/(16*DesiredBaudRate) - 1. Obviously the math doesnt always make an int. I would want to take that definition and use some round() function on it to make it into an int. However, this obviously will take some processor time every time I try to evaluate it supposing that there is no optimization for round(someDefinedNumber).
I have a definition for OSC_FREQ, USART_BAUD, and the factor 16 is obvious. The compiler will normally optimize this through arithmetic, but how should I go about rounding the number?
you could use the macro:
#define DIVIDE_ROUNDED(x,y) (((x)+(y)/2)/(y))
if x and y are literals then the expression should be
calculated at compile time and cause no runtime overhead.
(If y is something with a side-effect you probably
won't be completely happy with this macro)
#define DIVIDE_ROUNDED(x,y) (((x)/(float)(y))+0.5)
(OSC_FREQ / (16.0 * USART_BAUD)) - 0.5
There are no side-effect problems. All floating point arithmetic is done by the compiler at compile time and the result is cast to integer type at compile time too when assigning to the register.
Log in to post a comment.