/******************************************************************************
*@file  : app.c
*@brief : application
******************************************************************************/
#include "app.h"

/******************************************************************************
* @brief : enter standby.
* @param : None
* @return: None
******************************************************************************/
void Enter_LowPower_Standby(void)
{
	/*----------------进standy模式前设置-------------*/ 
    /* 使能RTC PCLK */
    SCU->IPCKENR1 |= BIT13;

	/*时钟切换到RCH*/
	SCU->CCR1 = 0;
    /* 关闭XTH、XTL、RC4M、32K 时钟  */
    SCU->RCHCR&= ~(1 << 16);        // RC4M Disable
    SCU->XTHCR &= ~(1 <<  0);       // XTH Disable

    SCU->STOPCFG |=  (1 << 0);          // RTC域写使能
    PMU_XTLCmd(PMU_STATE_DISABLE);      // XTL Disable
    PMU_RC32KCmd(PMU_STATE_DISABLE);    // RC32K Disable
    PMU_RTCClkCmd(PMU_STATE_DISABLE);   // RTCCLK Disable          
	
    /* PC13唤醒,默认上拉,下降沿唤醒*/
    PMU_PMUDomainPinMode(PMU_PIN_PC13, PMU_PIN_DIGITAL);
    PMU_PMUDomainPinPull(PMU_PIN_PC13, PMU_PIN_PULLUP);
    PMU_WakeupPinCmd(PMU_WAKEUP_PIN2, PMU_STATE_ENABLE);
    PMU_WakeupPinPolarityConfig(PMU_WAKEUP_PIN2, PMU_WAKEUP_POLARITY_FALLING);

    /* LVD Disable */
    SCU->LVDCFG &= ~(1 << 0);

    /* All Clock Disable */
    SCU->CLKOCR &= ~(1ul << 31);    // Buzzer2 Disable
    SCU->CLKOCR &= ~(1ul << 23);    // Buzzer1 Disable
	

    SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;   // disable systick        
    __set_PRIMASK(1);    // disable interrupt 
    SCB->ICSR = BIT25;   // clear systick pending bit 
	
    /*-----------进standy模式,等待唤醒--------*/
    PMU_EnterStandbyMode(PMU_LOWPOWRENTRY_WFI);
    
    SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk; /* Enable SysTick IRQ */               
    __set_PRIMASK(0);    // enable interrupt 
    while(1)
    {
        printfS("MCU never run here \r\n");
    }

}


/******************************************************************************
* @brief : app test.
* @param : None
* @return: None
******************************************************************************/
void APP_Test(void)
{
    PMU_Init();
    
    if(SET == PMU_GetFlagStatus(PMU_FLAG_WUPF2))
    {
        printfS("MCU Wakeup source --> Wakeup2 \r\n");        
    }
    
    System_Delay_MS(1500);
    
    printfS("MCU enter standby mode, MCU will wakeup by PC13 falling edge!\n");
    
    Enter_LowPower_Standby();

}








