Skip to content

Commit 34e43c7

Browse files
committed
stmhal: Improve efficiency of SysTick IRQ and HAL_Delay.
SysTick IRQ now increases millisecond counter directly (ie without calling HAL_IncTick). Provide our own version of HAL_Delay that does a wfi while waiting. This more than halves power consumption when running a loop containing a pyb.delay call. It used to be like this, but new version of HAL library regressed this feature.
1 parent 3475b04 commit 34e43c7

3 files changed

Lines changed: 18 additions & 2 deletions

File tree

stmhal/hal/src/stm32f4xx_hal.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@
9393
#define CMPCR_CMP_PD_BB (PERIPH_BB_BASE + (CMPCR_OFFSET * 32) + (CMP_PD_BitNumber * 4))
9494
/* Private macro -------------------------------------------------------------*/
9595
/* Private variables ---------------------------------------------------------*/
96-
static __IO uint32_t uwTick;
96+
__IO uint32_t uwTick;
9797

9898
/* Private function prototypes -----------------------------------------------*/
9999
/* Private functions ---------------------------------------------------------*/

stmhal/stm32f4xx_it.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,11 @@ void PendSV_Handler(void) {
173173
* @retval None
174174
*/
175175
void SysTick_Handler(void) {
176-
HAL_IncTick();
176+
// Instead of calling HAL_IncTick we do the increment here of the counter.
177+
// This is purely for efficiency, since SysTick is called 1000 times per
178+
// second at the highest interrupt priority.
179+
extern __IO uint32_t uwTick;
180+
uwTick += 1;
177181

178182
// Read the systick control regster. This has the side effect of clearing
179183
// the COUNTFLAG bit, which makes the logic in sys_tick_get_microseconds

stmhal/systick.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,18 @@
3333
#include "irq.h"
3434
#include "systick.h"
3535

36+
// We provide our own version of HAL_Delay that calls __WFI while waiting, in
37+
// order to reduce power consumption.
38+
void HAL_Delay(uint32_t Delay) {
39+
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+
}
47+
3648
bool sys_tick_has_passed(uint32_t start_tick, uint32_t delay_ms) {
3749
return HAL_GetTick() - start_tick >= delay_ms;
3850
}

0 commit comments

Comments
 (0)