From 40ffe6ecefb48c68b7d7b379689e8ad9e47858b5 Mon Sep 17 00:00:00 2001 From: robert-hh Date: Mon, 12 Feb 2024 20:34:15 +0100 Subject: [PATCH] rp2/machine_uart.c: Test for an invalid baud rate. The baud rate requested in the init call may not be achievable. This happens at least if the baud rate is too low or too high, but may as well happen at other baud rates. If the deviation is larger than 2 %, an error is raised. Signed-off-by: robert-hh --- ports/rp2/machine_uart.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ports/rp2/machine_uart.c b/ports/rp2/machine_uart.c index ccbf8f781a..0aa958c962 100644 --- a/ports/rp2/machine_uart.c +++ b/ports/rp2/machine_uart.c @@ -367,7 +367,11 @@ static void mp_machine_uart_init_helper(machine_uart_obj_t *self, size_t n_args, self->timeout_char = min_timeout_char; } - uart_init(self->uart, self->baudrate); + uint32_t new_baudrate = uart_init(self->uart, self->baudrate); + uint32_t baudrate_diff = new_baudrate > self->baudrate ? new_baudrate - self->baudrate : self->baudrate - new_baudrate; + if (baudrate_diff > (self->baudrate / 50)) { + mp_raise_ValueError(MP_ERROR_TEXT("Invalid baud rate")); + } uart_set_format(self->uart, self->bits, self->stop, self->parity); __DSB(); // make sure UARTLCR_H register is written to uart_set_fifo_enabled(self->uart, true);