UART Baud Rate Programming formula: Datasheet != Code

Hello,

I have a question about the baud rate calculation on Arduino Leonardo.

In the data sheet, the formula for UBRR value in normal mode is:

UBRRn = ( Fosc / 16 / BAUD ) - 1

But in HardwareSerial.cpp, the formula is the following:

UBBRn = (( F_CPU / 8 / BAUD ) - 1) / 2

And it gave some (little) differences. For example, if the F_CPU is 16MHz, for 57600Bauds, first will gave 16.3666, so nearest value would be 16. The second formula would gave 16.86, nearest value would be 17.

So why the formula inside the code is not the formula from the datasheet? Is it because we want to round down the value all the time? And if yes, why? Is it not better to use the nearest value possible?

Thank you

The first one divides by 16. The second one divides by 8 and then by 2.

And remember that integer maths completely ignores fractions. So 16.86 is treated as 16.

...R

Yes, but (X/16) - 1 is different from ((X/8) - 1 ) / 2...

If I keep the 16MHz CPU, with 57600Bauds, but in double speed mode this time, the results will be:

UBRRn = ( Fosc / 8 / BAUD ) - 1 = 33.777 --> 33 But UBBRn = (( Fosc / 4 / BAUD ) - 1) / 2 = 34.222 --> 34

So this time, the values will be different.