2424 * THE SOFTWARE.
2525 */
2626
27- #include STM32_HAL_H
28-
29- #include "py/obj.h"
27+ #include "py/mphal.h"
3028#include "irq.h"
3129#include "systick.h"
3230#include "pybthread.h"
3331
34- // We provide our own version of HAL_Delay that calls __WFI while waiting, in
35- // order to reduce power consumption.
36- // Note: Upon entering this function we may or may not have the GIL.
32+ extern __IO uint32_t uwTick ;
33+
34+ // We provide our own version of HAL_Delay that calls __WFI while waiting,
35+ // and works when interrupts are disabled. This function is intended to be
36+ // used only by the ST HAL functions.
3737void HAL_Delay (uint32_t Delay ) {
3838 if (query_irq () == IRQ_STATE_ENABLED ) {
3939 // IRQs enabled, so can use systick counter to do the delay
40- extern __IO uint32_t uwTick ;
40+ uint32_t start = uwTick ;
41+ // Wraparound of tick is taken care of by 2's complement arithmetic.
42+ while (uwTick - start < Delay ) {
43+ // Enter sleep mode, waiting for (at least) the SysTick interrupt.
44+ __WFI ();
45+ }
46+ } else {
47+ // IRQs disabled, use mp_hal_delay_ms routine.
48+ mp_hal_delay_ms (Delay );
49+ }
50+ }
51+
52+ // Core delay function that does an efficient sleep and may switch thread context.
53+ // Note: Upon entering this function we may or may not have the GIL.
54+ void mp_hal_delay_ms (mp_uint_t Delay ) {
55+ if (query_irq () == IRQ_STATE_ENABLED ) {
56+ // IRQs enabled, so can use systick counter to do the delay
4157 uint32_t start = uwTick ;
4258 // Wraparound of tick is taken care of by 2's complement arithmetic.
4359 while (uwTick - start < Delay ) {
@@ -64,11 +80,11 @@ void HAL_Delay(uint32_t Delay) {
6480}
6581
6682// delay for given number of microseconds
67- void sys_tick_udelay ( uint32_t usec ) {
83+ void mp_hal_delay_us ( mp_uint_t usec ) {
6884 if (query_irq () == IRQ_STATE_ENABLED ) {
6985 // IRQs enabled, so can use systick counter to do the delay
70- uint32_t start = sys_tick_get_microseconds ();
71- while (sys_tick_get_microseconds () - start < usec ) {
86+ uint32_t start = mp_hal_ticks_us ();
87+ while (mp_hal_ticks_us () - start < usec ) {
7288 }
7389 } else {
7490 // IRQs disabled, so need to use a busy loop for the delay
@@ -92,11 +108,15 @@ void sys_tick_wait_at_least(uint32_t start_tick, uint32_t delay_ms) {
92108 }
93109}
94110
111+ mp_uint_t mp_hal_ticks_ms (void ) {
112+ return uwTick ;
113+ }
114+
95115// The SysTick timer counts down at 168 MHz, so we can use that knowledge
96116// to grab a microsecond counter.
97117//
98118// We assume that HAL_GetTickis returns milliseconds.
99- uint32_t sys_tick_get_microseconds (void ) {
119+ mp_uint_t mp_hal_ticks_us (void ) {
100120 mp_uint_t irq_state = disable_irq ();
101121 uint32_t counter = SysTick -> VAL ;
102122 uint32_t milliseconds = HAL_GetTick ();
0 commit comments