Calculate UART Baud Rate

Some AVR datasheets give the following formula for calculating baud rates:

(F_CPU/(UART_BAUD_RATE*16UL)-1UL)

Unfortunately the formula does not work with all combinations of clock speeds and baud rates due to integer truncation during the division operator.

When doing integer division it is usually better to round to the nearest integer, rather than to the lowest. To do this add 0.5 (i. e. half the value of the denominator) to the numerator before the division. The formula to use is then as follows.

((F_CPU + UART_BAUD_RATE * 8UL) / (UART_BAUD_RATE * 16UL) - 1UL)

This is also the way it is implemented in <util/setbaud.h >.