From 187b9c4c4eb324d2476e3a6114f373c39f756de1 Mon Sep 17 00:00:00 2001 From: Daniel Fanache Date: Thu, 15 Oct 2020 21:14:05 +0100 Subject: [PATCH] Trigger STM32G4xx bootloader through flash option bit. Uses Zephyr flash driver. Currently only supported on the STM32G4xx devices. --- src/hardware.cpp | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/hardware.cpp b/src/hardware.cpp index 6d9a9b2..4e07fa7 100644 --- a/src/hardware.cpp +++ b/src/hardware.cpp @@ -20,6 +20,7 @@ #include #include +#include #include LOG_MODULE_REGISTER(hardware, CONFIG_HW_LOG_LEVEL); @@ -27,7 +28,6 @@ LOG_MODULE_REGISTER(hardware, CONFIG_HW_LOG_LEVEL); void start_stm32_bootloader() { #if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), boot0)) - // pin is connected to BOOT0 via resistor and capacitor const struct device *dev = device_get_binding(DT_GPIO_LABEL(BOOT0_GPIO, gpios)); gpio_pin_configure(dev, DT_GPIO_PIN(BOOT0_GPIO, gpios), @@ -35,6 +35,33 @@ void start_stm32_bootloader() k_sleep(K_MSEC(100)); // wait for capacitor at BOOT0 pin to charge up reset_device(); +#elif defined(CONFIG_SOC_SERIES_STM32G4X) + const struct device *flash = device_get_binding(DT_LABEL(DT_NODELABEL(flash0))); + flash_write_protection_set(flash, false); + // Set proper bits for booting the embedded bootloader (see table + // 5 in section 2.6.1 in document RM0440) + + // nBOOT0: nBOOT0 option bit (equivalent to the BOOT0 pin) + // nSWBOOT0: 0: BOOT0 taken from the option bit nBOOT0 + // nSWBOOT0: 1: BOOT0 taken from PB8/BOOT0 pin + // nBOOT1: Together with the BOOT0 pin, this bit selects boot mode + // from the Flash main memory, SRAM1 or the System memory. + + FLASH->OPTR &= ~(FLASH_OPTR_nSWBOOT0 | FLASH_OPTR_nBOOT0); + FLASH->OPTR |= FLASH_OPTR_nBOOT1; + + // Save the current registers in flash, to be reloaded at reset + FLASH->CR |= FLASH_CR_OPTSTRT; + k_sleep(K_MSEC(20)); + + // Reload the option registers from flash; should trigger a system + // reset. + FLASH->CR |= FLASH_CR_OBL_LAUNCH; + + // If OBL_LAUNCH did not reset (it should), we'll force it by + // first locking back the flash registers and going for a reboot. + flash_write_protection_set(flash, true); + reset_device(); #endif }