Skip to content

Commit a2fa47b

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 43c65f4 commit a2fa47b

File tree

1 file changed

+11
-24
lines changed

1 file changed

+11
-24
lines changed

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

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

289289
void HardwareSerial::begin(unsigned long baud, byte config)
290290
{
291-
uint16_t baud_setting;
292-
bool use_u2x = true;
293-
294-
#if F_CPU == 16000000UL
295-
// hardcoded exception for compatibility with the bootloader shipped
296-
// with the Duemilanove and previous boards and the firmware on the 8U2
297-
// on the Uno and Mega 2560.
298-
if (baud == 57600) {
299-
use_u2x = false;
300-
}
301-
#endif
302-
303-
try_again:
304-
305-
if (use_u2x) {
306-
*_ucsra = 1 << _u2x;
307-
baud_setting = (F_CPU / 4 / baud - 1) / 2;
308-
} else {
291+
// Try u2x mode first
292+
uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
293+
*_ucsra = 1 << _u2x;
294+
295+
// hardcoded exception for 57600 for compatibility with the bootloader
296+
// shipped with the Duemilanove and previous boards and the firmware
297+
// on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
298+
// be > 4095, so switch back to non-u2x mode if the baud rate is too
299+
// low.
300+
if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
301+
{
309302
*_ucsra = 0;
310303
baud_setting = (F_CPU / 8 / baud - 1) / 2;
311304
}
312-
313-
if ((baud_setting > 4095) && use_u2x)
314-
{
315-
use_u2x = false;
316-
goto try_again;
317-
}
318305

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

0 commit comments

Comments
 (0)