Skip to content

Commit 3f8b472

Browse files
committed
Revise us delay to include interrupt/non-interrupt versions
1 parent 1a7060a commit 3f8b472

File tree

1 file changed

+30
-6
lines changed
  • ports/stm32f4/common-hal/microcontroller

1 file changed

+30
-6
lines changed

ports/stm32f4/common-hal/microcontroller/__init__.c

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,39 @@
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+
4457
void common_hal_mcu_delay_us(uint32_t delay) {
45-
// sys freq is always a multiple of 2MHz, so division here won't lose precision
46-
const uint32_t ucount = HAL_RCC_GetSysClockFreq() / 2000000 * delay / 2;
47-
for (uint32_t count = 0; ++count <= ucount;) {
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+
(void)start;
68+
for (uint32_t count = 0; ++count <= ucount;) {
69+
}
70+
}
4871
}
4972

5073
volatile uint32_t nesting_count = 0;
74+
5175
void common_hal_mcu_disable_interrupts(void) {
5276
__disable_irq();
5377
__DMB();
@@ -58,7 +82,7 @@ void common_hal_mcu_enable_interrupts(void) {
5882
if (nesting_count == 0) {
5983
// This is very very bad because it means there was mismatched disable/enables so we
6084
// "HardFault".
61-
HardFault_Handler();
85+
asm("bkpt");
6286
}
6387
nesting_count--;
6488
if (nesting_count > 0) {

0 commit comments

Comments
 (0)