Skip to content

Commit 6cce478

Browse files
matthijskooijmancmaglie
authored andcommitted
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 db5da36 commit 6cce478

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
@@ -283,33 +283,20 @@ HardwareSerial::HardwareSerial(
283283

284284
void HardwareSerial::begin(unsigned long baud, byte config)
285285
{
286-
uint16_t baud_setting;
287-
bool use_u2x = true;
288-
289-
#if F_CPU == 16000000UL
290-
// hardcoded exception for compatibility with the bootloader shipped
291-
// with the Duemilanove and previous boards and the firmware on the 8U2
292-
// on the Uno and Mega 2560.
293-
if (baud == 57600) {
294-
use_u2x = false;
295-
}
296-
#endif
297-
298-
try_again:
299-
300-
if (use_u2x) {
301-
*_ucsra = 1 << _u2x;
302-
baud_setting = (F_CPU / 4 / baud - 1) / 2;
303-
} else {
286+
// Try u2x mode first
287+
uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
288+
*_ucsra = 1 << _u2x;
289+
290+
// hardcoded exception for 57600 for compatibility with the bootloader
291+
// shipped with the Duemilanove and previous boards and the firmware
292+
// on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
293+
// be > 4095, so switch back to non-u2x mode if the baud rate is too
294+
// low.
295+
if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
296+
{
304297
*_ucsra = 0;
305298
baud_setting = (F_CPU / 8 / baud - 1) / 2;
306299
}
307-
308-
if ((baud_setting > 4095) && use_u2x)
309-
{
310-
use_u2x = false;
311-
goto try_again;
312-
}
313300

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

0 commit comments

Comments
 (0)