Simplify HardwareSerial::begin()

This simplifies the baud rate calculation, removing the need for a goto
and shortening the code a bit. Other than that, this code should not use
any different settings than before.

Code was suggested by Rob Tillaart on github.

Closes: #1262
This commit is contained in:
Matthijs Kooijman 2013-04-19 16:32:33 +02:00 committed by Cristian Maglie
parent db5da3691e
commit 6cce4787bf
1 changed files with 10 additions and 23 deletions

View File

@ -283,33 +283,20 @@ HardwareSerial::HardwareSerial(
void HardwareSerial::begin(unsigned long baud, byte config) void HardwareSerial::begin(unsigned long baud, byte config)
{ {
uint16_t baud_setting; // Try u2x mode first
bool use_u2x = true; uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
*_ucsra = 1 << _u2x;
#if F_CPU == 16000000UL // hardcoded exception for 57600 for compatibility with the bootloader
// hardcoded exception for compatibility with the bootloader shipped // shipped with the Duemilanove and previous boards and the firmware
// with the Duemilanove and previous boards and the firmware on the 8U2 // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
// on the Uno and Mega 2560. // be > 4095, so switch back to non-u2x mode if the baud rate is too
if (baud == 57600) { // low.
use_u2x = false; if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
} {
#endif
try_again:
if (use_u2x) {
*_ucsra = 1 << _u2x;
baud_setting = (F_CPU / 4 / baud - 1) / 2;
} else {
*_ucsra = 0; *_ucsra = 0;
baud_setting = (F_CPU / 8 / baud - 1) / 2; baud_setting = (F_CPU / 8 / baud - 1) / 2;
} }
if ((baud_setting > 4095) && use_u2x)
{
use_u2x = false;
goto try_again;
}
// assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
*_ubrrh = baud_setting >> 8; *_ubrrh = baud_setting >> 8;