Skip to content

Commit 4c7d799

Browse files
committed
stmhal/uart: Add check that UART id is valid for the given board.
Previous to this patch trying to construct, but not init, a UART that didn't exist on the target board would actually succeed. Only when initialising the UART would it then raise an exception that the UART does not exist. This patch adds an explicit check that the constructed UART does in fact exist for the given board.
1 parent aaab6a9 commit 4c7d799

1 file changed

Lines changed: 43 additions & 1 deletion

File tree

stmhal/uart.c

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,48 @@ void uart_deinit(void) {
109109
}
110110
}
111111

112+
STATIC bool uart_exists(int uart_id) {
113+
if (uart_id > MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all))) {
114+
// safeguard against pyb_uart_obj_all array being configured too small
115+
return false;
116+
}
117+
switch (uart_id) {
118+
#if defined(MICROPY_HW_UART1_TX) && defined(MICROPY_HW_UART1_RX)
119+
case PYB_UART_1: return true;
120+
#endif
121+
122+
#if defined(MICROPY_HW_UART2_TX) && defined(MICROPY_HW_UART2_RX)
123+
case PYB_UART_2: return true;
124+
#endif
125+
126+
#if defined(MICROPY_HW_UART3_TX) && defined(MICROPY_HW_UART3_RX)
127+
case PYB_UART_3: return true;
128+
#endif
129+
130+
#if defined(MICROPY_HW_UART4_TX) && defined(MICROPY_HW_UART4_RX)
131+
case PYB_UART_4: return true;
132+
#endif
133+
134+
#if defined(MICROPY_HW_UART5_TX) && defined(MICROPY_HW_UART5_RX)
135+
case PYB_UART_5: return true;
136+
#endif
137+
138+
#if defined(MICROPY_HW_UART6_TX) && defined(MICROPY_HW_UART6_RX)
139+
case PYB_UART_6: return true;
140+
#endif
141+
142+
#if defined(MICROPY_HW_UART7_TX) && defined(MICROPY_HW_UART7_RX)
143+
case PYB_UART_7: return true;
144+
#endif
145+
146+
#if defined(MICROPY_HW_UART8_TX) && defined(MICROPY_HW_UART8_RX)
147+
case PYB_UART_8: return true;
148+
#endif
149+
150+
default: return false;
151+
}
152+
}
153+
112154
// assumes Init parameters have been set up correctly
113155
STATIC bool uart_init2(pyb_uart_obj_t *uart_obj) {
114156
USART_TypeDef *UARTx;
@@ -650,7 +692,7 @@ STATIC mp_obj_t pyb_uart_make_new(const mp_obj_type_t *type, mp_uint_t n_args, m
650692
}
651693
} else {
652694
uart_id = mp_obj_get_int(args[0]);
653-
if (uart_id < 1 || uart_id > MP_ARRAY_SIZE(MP_STATE_PORT(pyb_uart_obj_all))) {
695+
if (!uart_exists(uart_id)) {
654696
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) does not exist", uart_id));
655697
}
656698
}

0 commit comments

Comments
 (0)