Skip to content

Commit a981366

Browse files
committed
uart_set_baudrate should return actual rate set even in case of out of range parameters
1 parent 4cc1efa commit a981366

File tree

2 files changed

+11
-8
lines changed
  • src
    • common/pico_base/include/pico
    • rp2_common/hardware_uart

2 files changed

+11
-8
lines changed

src/common/pico_base/include/pico/error.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ enum {
1616
PICO_ERROR_TIMEOUT = -1,
1717
PICO_ERROR_GENERIC = -2,
1818
PICO_ERROR_NO_DATA = -3,
19+
PICO_ERROR_OUT_OF_RANGE = -4,
1920
};
2021

2122
#endif

src/rp2_common/hardware_uart/uart.c

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,23 +75,25 @@ uint uart_set_baudrate(uart_inst_t *uart, uint baudrate) {
7575
uint32_t baud_rate_div = (8 * clock_get_hz(clk_peri) / baudrate);
7676
uint32_t baud_ibrd = baud_rate_div >> 7;
7777
uint32_t baud_fbrd = ((baud_rate_div & 0x7f) + 1) / 2;
78-
invalid_params_if(UART, (baud_ibrd > 65535) || (baud_ibrd == 0));
78+
79+
if (baud_ibrd == 0) {
80+
baud_ibrd = 1;
81+
baud_fbrd = 0;
82+
} else if (baud_ibrd >= 65535) {
83+
baud_ibrd = 65535;
84+
baud_fbrd = 0;
85+
}
7986

8087
// Load PL011's baud divisor registers
8188
uart_get_hw(uart)->ibrd = baud_ibrd;
82-
if (baud_ibrd == 65535) {
83-
uart_get_hw(uart)->fbrd = 0;
84-
} else {
85-
uart_get_hw(uart)->fbrd = baud_fbrd;
86-
}
89+
uart_get_hw(uart)->fbrd = baud_fbrd;
8790

8891
// PL011 needs a (dummy) line control register write to latch in the
8992
// divisors. We don't want to actually change LCR contents here.
9093
hw_set_bits(&uart_get_hw(uart)->lcr_h, 0);
9194

9295
// See datasheet
93-
uint baud = (4 * clock_get_hz(clk_peri)) / (64 * baud_ibrd + baud_fbrd);
94-
return baud;
96+
return (4 * clock_get_hz(clk_peri)) / (64 * baud_ibrd + baud_fbrd);
9597
}
9698
/// \end::uart_set_baudrate[]
9799

0 commit comments

Comments
 (0)