3939#include "supervisor/filesystem.h"
4040#include "supervisor/shared/safe_mode.h"
4141
42- // This routine should work even when interrupts are disabled. Used by OneWire
43- // for precise timing.
42+ #include "stm32f4xx_hal.h"
43+
44+ //tested divisor value for busy loop in us delay
45+ #define LOOP_TICKS 12
46+
47+ STATIC uint32_t get_us (void ) {
48+ uint32_t ticks_per_us = HAL_RCC_GetSysClockFreq ()/1000000 ;
49+ uint32_t micros , sys_cycles ;
50+ do {
51+ micros = ticks_ms ;
52+ sys_cycles = SysTick -> VAL ; //counts backwards
53+ } while (micros != ticks_ms ); //try again if ticks_ms rolled over
54+ return (micros * 1000 ) + (ticks_per_us * 1000 - sys_cycles ) / ticks_per_us ;
55+ }
56+
4457void common_hal_mcu_delay_us (uint32_t delay ) {
45- //TODO: implement equivalent of mp_hal_delay_us(delay);
46- //this is fairly annoying in the STM32 HAL
58+ if (__get_PRIMASK () == 0x00000000 ) {
59+ //by default use ticks_ms
60+ uint32_t start = get_us ();
61+ while (get_us ()- start < delay ) {
62+ __asm__ __volatile__("nop" );
63+ }
64+ } else {
65+ //when SysTick is disabled, approximate with busy loop
66+ const uint32_t ucount = HAL_RCC_GetSysClockFreq () / 1000000 * delay / LOOP_TICKS ;
67+ for (uint32_t count = 0 ; ++ count <= ucount ;) {
68+ }
69+ }
4770}
4871
49- void common_hal_mcu_disable_interrupts () {
72+ volatile uint32_t nesting_count = 0 ;
73+
74+ void common_hal_mcu_disable_interrupts (void ) {
75+ __disable_irq ();
76+ __DMB ();
77+ nesting_count ++ ;
5078}
5179
52- void common_hal_mcu_enable_interrupts () {
80+ void common_hal_mcu_enable_interrupts (void ) {
81+ if (nesting_count == 0 ) {
82+ // This is very very bad because it means there was mismatched disable/enables so we
83+ // "HardFault".
84+ asm("bkpt" );
85+ }
86+ nesting_count -- ;
87+ if (nesting_count > 0 ) {
88+ return ;
89+ }
90+ __DMB ();
91+ __enable_irq ();
5392}
5493
5594void common_hal_mcu_on_next_reset (mcu_runmode_t runmode ) {
@@ -58,7 +97,7 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) {
5897}
5998
6099void common_hal_mcu_reset (void ) {
61- filesystem_flush ();
100+ filesystem_flush (); //TODO: implement as part of flash improvements
62101 NVIC_SystemReset ();
63102}
64103
0 commit comments