#include "mcu_power_sleep.h" #include "bsp/ml5238.h" #include "bsp/cs1180.h" #include "bsp/gpio.h" #include "bsp/spi.h" #include "bsp/uart.h" #include "bsp/i2c.h" #include "bsp/shark_rtc.h" #include "app/sox/iostate.h" extern void system_clock_24m_irc8m(void); extern void system_clock_config(void); extern void SystemCoreClockUpdate(void); extern void current_calibrate(void); extern void adc_init(void); extern void adc_deinit(void); static uint32_t _sleep_second_time = 0; static void post_deepsleep(void); #define WDOG_TIME_FOR_SLEEP 15 #define RTC_ALARM_FOR_SLEEP 10 //rtc alarm time MUST be small than wdog time!!!! uint32_t get_system_sleep_time(void){ return _sleep_second_time; } static void enable_wakeup_irq(void){ charger_detect_irq_enable(1); hall_1_detect_irq_enable(1); //hall_2_detect_irq_enable(1); shark_rtc_start_alarm(RTC_ALARM_FOR_SLEEP); } static void disable_wakeup_irq(void){ shark_rtc_stop_alarm(); charger_detect_irq_enable(0); hall_1_detect_irq_enable(0); //hall_2_detect_irq_enable(0); } static void pre_deepsleep(void){ CS1180_PWR_ENABLE(0); shark_uart_deinit(SHARK_UART0); shark_uart_deinit(SHARK_UART1); wdog_reload(); ml5238_power_save(1); //call, before spi0_deinit spi0_deinit(); spi1_deinit(); gd32_i2c_deinit(0); adc_deinit(); if (AUX_VOL_IS_OPEN()) { AUX_VOL_OPEN(0);//we should close small power, before dcdc close delay_us(1000); } wdog_reload(); io_state()->aux_lock_detect = 0; DCDC_VOL_OPEN(0); delay_us(1000); // give 1s to wait small current short, when dcdc is closed AUX_VOL_OPEN(1); delay_us(5000); //give 5s to detect if the small current is short if (io_state()->aux_lock_detect){ post_deepsleep(); return; } wdog_set_timeout(WDOG_TIME_FOR_SLEEP); } static void post_deepsleep(void){ DCDC_VOL_OPEN(1); SystemInit(); system_clock_config(); SystemCoreClockUpdate(); spi0_init(); ml5238_power_save(0); CS1180_PWR_ENABLE(1); cs1180_adc_init(); shark_uart_init(SHARK_UART0); shark_uart_init(SHARK_UART1); gd32_i2c_init(0, 100* 1000); adc_init(); wdog_set_timeout(4); current_calibrate(); wdog_reload(); printf("Sleep Exit, Total sleep time = %d s\n", _sleep_second_time); } void mcu_enter_deepsleep(void){ pre_deepsleep(); enable_wakeup_irq(); u32 start_time = shark_rtc_get_second(); pmu_to_deepsleepmode(PMU_LDO_LOWPOWER, WFI_CMD); u32 end_time = shark_rtc_get_second(); if (end_time >= start_time) { _sleep_second_time += (end_time - start_time); }else { //rtc second wrap _sleep_second_time += (60 - start_time + end_time); } disable_wakeup_irq(); post_deepsleep(); }