From 50572b08874e1aa2674112089b718d854bc15d49 Mon Sep 17 00:00:00 2001 From: robert-hh Date: Wed, 16 Aug 2023 16:00:43 +0200 Subject: [PATCH] mimxrt: Fix the UART.deinit() and uart_deinit_all() behaviour. The code did not check at deinit whether a UART was initialized. That did not matter for all MCU's except MIMXRT1176, which crashes at the second soft reset in a row. But since it is a general problem to use UART methods of a UART which has been deinitialized, checks were added to all methods for a clear response instead of e.g. a crash. Signed-off-by: robert-hh --- ports/mimxrt/machine_uart.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/ports/mimxrt/machine_uart.c b/ports/mimxrt/machine_uart.c index 17d789886c618..370be9d7aa4b1 100644 --- a/ports/mimxrt/machine_uart.c +++ b/ports/mimxrt/machine_uart.c @@ -81,6 +81,7 @@ static const iomux_table_t iomux_table_uart[] = { static const iomux_table_t iomux_table_uart_cts_rts[] = { IOMUX_TABLE_UART_CTS_RTS }; +static bool uart_active[MICROPY_HW_UART_NUM]; STATIC const char *_parity_name[] = {"None", "", "0", "1"}; // Is defined as 0, 2, 3 STATIC const char *_invert_name[] = {"None", "INV_TX", "INV_RX", "INV_TX|INV_RX"}; @@ -306,6 +307,7 @@ STATIC mp_obj_t machine_uart_init_helper(machine_uart_obj_t *self, size_t n_args self->lpuart->STAT |= 1 << LPUART_STAT_BRK13_SHIFT; LPUART_EnableTx(self->lpuart, true); } + uart_active[self->id] = true; return MP_OBJ_FROM_PTR(self); } @@ -351,7 +353,10 @@ MP_DEFINE_CONST_FUN_OBJ_KW(machine_uart_init_obj, 1, machine_uart_init); // uart.deinit() STATIC mp_obj_t machine_uart_deinit(mp_obj_t self_in) { machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in); - LPUART_Deinit(self->lpuart); + if (uart_active[self->id]) { + LPUART_Deinit(self->lpuart); + } + uart_active[self->id] = false; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_deinit_obj, machine_uart_deinit); @@ -384,9 +389,10 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_txdone_obj, machine_uart_txdone); // Deinitialize all defined UARTs void machine_uart_deinit_all(void) { - for (int i = 0; i < sizeof(uart_index_table); i++) { - if (uart_index_table[i] != 0) { + for (int i = 0; i < MICROPY_HW_UART_NUM; i++) { + if (uart_index_table[i] != 0 && uart_active[i] == true) { LPUART_Deinit(uart_base_ptr_table[uart_index_table[i]]); + uart_active[i] = false; } } }