Skip to content

Commit 28fe88c

Browse files
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: arduino#1262
1 parent f60d5cc commit 28fe88c

File tree

1 file changed

+11
-24
lines changed

1 file changed

+11
-24
lines changed

Diff for: hardware/arduino/cores/arduino/HardwareSerial.cpp

+11-24
Original file line numberDiff line numberDiff line change
@@ -264,33 +264,20 @@ void HardwareSerial::begin(unsigned long baud)
264264

265265
void HardwareSerial::begin(unsigned long baud, byte config)
266266
{
267-
uint16_t baud_setting;
268-
bool use_u2x = true;
269-
270-
#if F_CPU == 16000000UL
271-
// hardcoded exception for compatibility with the bootloader shipped
272-
// with the Duemilanove and previous boards and the firmware on the 8U2
273-
// on the Uno and Mega 2560.
274-
if (baud == 57600) {
275-
use_u2x = false;
276-
}
277-
#endif
278-
279-
try_again:
280-
281-
if (use_u2x) {
282-
*_ucsra = 1 << U2X0;
283-
baud_setting = (F_CPU / 4 / baud - 1) / 2;
284-
} else {
267+
// Try u2x mode first
268+
uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
269+
*_ucsra = 1 << U2X0;
270+
271+
// hardcoded exception for 57600 for compatibility with the bootloader
272+
// shipped with the Duemilanove and previous boards and the firmware
273+
// on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
274+
// be > 4095, so switch back to non-u2x mode if the baud rate is too
275+
// low.
276+
if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
277+
{
285278
*_ucsra = 0;
286279
baud_setting = (F_CPU / 8 / baud - 1) / 2;
287280
}
288-
289-
if ((baud_setting > 4095) && use_u2x)
290-
{
291-
use_u2x = false;
292-
goto try_again;
293-
}
294281

295282
// assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
296283
*_ubrrh = baud_setting >> 8;

0 commit comments

Comments
 (0)