From fa4f717051ae75867c697b624bf35db72e9ac7a3 Mon Sep 17 00:00:00 2001 From: jaseg Date: Sat, 6 Jul 2019 15:47:01 +0900 Subject: Add switch gpio, improve sleep scheduling --- main.c | 53 ++++++++++++++++++++++++++++------------------------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/main.c b/main.c index 39f5452..2502be5 100644 --- a/main.c +++ b/main.c @@ -93,18 +93,6 @@ void rtc_set_alarm_rel_sec(uint32_t value) { rtc_set_alarm_sec(rtc_time() + value); } -void switch_output_enable() { - uint32_t now = rtc_time(); - if (now/300 % 24 == 0) - GPIOC->ODR |= 1<<14; - else - GPIOC->ODR &= ~(1<<14); -} - -void switch_output_disable() { - GPIOC->ODR &= ~(1<<14); -} - int main(void){ /* We're starting out from HSI@8MHz */ SystemCoreClockUpdate(); @@ -115,8 +103,7 @@ int main(void){ /* Turn on lots of neat things */ RCC->APB2ENR |= RCC_APB2ENR_IOPCEN; RCC->APB1ENR |= RCC_APB1ENR_BKPEN | RCC_APB1ENR_PWREN; - PWR->CR = PWR_CR_PDDS | PWR_CR_DBP; - SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* Use deep sleep mode */ + PWR->CR = PWR_CR_DBP; GPIOC->CRH |= (0<CSR & PWR_CSR_WUF)) /* This reset wasn't caused by the RTC alarm */ REBOOT_REGISTER++; + uint32_t now = rtc_time(); + bool switch_on = false; if (REBOOT_REGISTER > 1) { /* We have rebooted since initial bring-up */ /* Give status indication and active output as fail-safe */ - GPIOC->ODR &= ~(1<<13); - for (int i=0; i<5000; i++) - asm volatile ("nop"); - GPIOC->ODR |= 1<<13; + if ((now&3) == 0) { + GPIOC->ODR &= ~(1<<13); + for (int i=0; i<5000; i++) + asm volatile ("nop"); + GPIOC->ODR |= 1<<13; + } + + switch_on = true; - switch_output_enable(); } else { - uint32_t now = rtc_time(); - if (now >= TARGET_DATE - (DAY_SECONDS*24) && now < TARGET_DATE) - switch_output_enable(); - else - switch_output_disable(); + switch_on = (now >= TARGET_DATE - (DAY_SECONDS*24) && now < TARGET_DATE); + } + + if (switch_on && now/300 % 24 == 0) { + GPIOC->ODR |= 1<<14; + + /* Go to sleep mode to keep GPIO active */ + PWR->CR &= ~PWR_CR_PDDS; + SCB->SCR &= ~(SCB_SCR_SLEEPDEEP_Msk); /* Use deep sleep mode */ + + } else { + GPIOC->ODR &= ~(1<<14); + + /* Go to standby mode to reduce power consumption */ + PWR->CR = PWR_CR_PDDS; + SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* Use deep sleep mode */ } - PWR->CR |= PWR_CR_CWUF; + PWR->CR |= PWR_CR_CWUF; /* This has 2 cycles latency, thus the NOPs */ asm volatile ("nop"); asm volatile ("nop"); asm volatile ("wfe"); -- cgit