Skip to content

Instantly share code, notes, and snippets.

@zsellera
Created March 19, 2021 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zsellera/21ad396f35852a039444c782a69e142e to your computer and use it in GitHub Desktop.
Save zsellera/21ad396f35852a039444c782a69e142e to your computer and use it in GitHub Desktop.
// see kucu.io for further details
#include "main.h"
#include "power.h"
#include <stdbool.h>
#include "FreeRTOS.h"
#include "task.h"
#include "stm32l4xx_ll_rtc.h"
#include "stm32l4xx_ll_pwr.h"
#define POWER_REQUIRED_TASK_COUNT_TO_STOP 2
static volatile bool can_stop = false;
static volatile int stop_enabler_count = 0;
void power_pre_sleep_processing() {
if (can_stop) {
LL_RCC_SetClkAfterWakeFromStop(LL_RCC_STOP_WAKEUPCLOCK_MSI);
LL_PWR_SetPowerMode(LL_PWR_MODE_STOP2);
LL_LPM_EnableDeepSleep();
SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;
}
}
void power_post_sleep_processing() {
if (can_stop) {
SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk;
LL_LPM_EnableSleep();
}
}
void power_deepsleep_allow() {
portENTER_CRITICAL();
stop_enabler_count++;
can_stop = (stop_enabler_count == POWER_REQUIRED_TASK_COUNT_TO_STOP);
portEXIT_CRITICAL();
}
void power_deepsleep_prevent() {
portENTER_CRITICAL();
stop_enabler_count--;
can_stop = (stop_enabler_count == POWER_REQUIRED_TASK_COUNT_TO_STOP);
portEXIT_CRITICAL();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment