diff --git a/ports/stm/common-hal/microcontroller/__init__.c b/ports/stm/common-hal/microcontroller/__init__.c index a9c9b76849d..977ff3d074f 100644 --- a/ports/stm/common-hal/microcontroller/__init__.c +++ b/ports/stm/common-hal/microcontroller/__init__.c @@ -61,6 +61,11 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { if (runmode == RUNMODE_BOOTLOADER) { next_reset_to_bootloader = true; } + #if BOARD_UF2_STM32F_BOOTLOADER + if (runmode == RUNMODE_UF2) { + next_reset_to_bootloader = true; + } + #endif } void common_hal_mcu_reset(void) { @@ -69,7 +74,7 @@ void common_hal_mcu_reset(void) { if (next_reset_to_bootloader) { reset_to_bootloader(); } else { - NVIC_SystemReset(); + reset_cpu(); } } diff --git a/ports/stm/mpconfigport.h b/ports/stm/mpconfigport.h index afa9aa3685c..01c65541db8 100644 --- a/ports/stm/mpconfigport.h +++ b/ports/stm/mpconfigport.h @@ -24,6 +24,11 @@ extern uint8_t _ld_default_stack_size; #ifndef BOARD_VTOR_DEFER #define BOARD_VTOR_DEFER (0) #endif +// The board runs the uf2-stm32f bootloader (MakeCode Arcade consoles), which +// reads RTC->BKP0R on reset to choose between UF2 mode and the application. +#ifndef BOARD_UF2_STM32F_BOOTLOADER +#define BOARD_UF2_STM32F_BOOTLOADER (0) +#endif #ifndef BOARD_NO_VBUS_SENSE #define BOARD_NO_VBUS_SENSE (0) #endif diff --git a/ports/stm/supervisor/port.c b/ports/stm/supervisor/port.c index 6252ba3c8c0..79f6303fcc5 100644 --- a/ports/stm/supervisor/port.c +++ b/ports/stm/supervisor/port.c @@ -398,8 +398,24 @@ void reset_port(void) { #endif } +#if BOARD_UF2_STM32F_BOOTLOADER +// uf2-stm32f (https://github.com/mmoskal/uf2-stm32f) reads RTC->BKP0R on reset. +// With no signature it starts UF2 mode and, once USB enumerates, stays there. +// port_init() resets the backup domain, so this is written just before reset. +#define UF2_STM32F_BOOT_SIGNATURE 0x71a21877 +#define UF2_STM32F_APP_SIGNATURE 0x24a22d12 + +static void set_uf2_stm32f_signature(uint32_t signature) { + __HAL_RCC_PWR_CLK_ENABLE(); + HAL_PWR_EnableBkUpAccess(); + RTC->BKP0R = signature; +} +#endif + void reset_to_bootloader(void) { - #if CPY_STM32F4 + #if BOARD_UF2_STM32F_BOOTLOADER + set_uf2_stm32f_signature(UF2_STM32F_BOOT_SIGNATURE); + #elif CPY_STM32F4 // Record the request and reset, rather than jumping from a running // application. check_enter_bootloader() jumps on the way back up. port_set_saved_word(BOOTLOADER_MAGIC | @@ -413,6 +429,9 @@ void reset_to_bootloader(void) { } void reset_cpu(void) { + #if BOARD_UF2_STM32F_BOOTLOADER + set_uf2_stm32f_signature(UF2_STM32F_APP_SIGNATURE); + #endif NVIC_SystemReset(); }