#include "ACM32Fxx_HAL.h"

/*****************************************************************
@功能	进入Stop低功耗模式，关闭Eflash,并在Ram中运行
@参数	无
@返回	无
******************************************************************/
void Enter_Stop_Ram(void)
{
	volatile uint32_t i;
    
    SysTick->CTRL = 0;              //SysTick Off
	__set_PRIMASK(1);               // disable interrupt 

   /* STOP 模式下关闭LDO12、RC64M */
    SCU->STOPCFG   |=  (1 << 3);    //STOP 模式下关闭 RC64M
    SCU->STOPCFG   |=  (1 << 9);    //STOP 模式下进入LPSTOP
    
    /* All Clock Disable */
    SCU->CLKOCR &= ~(1ul << 31);    // Buzzer2 Disable
    SCU->CLKOCR &= ~(1ul << 23);    // Buzzer1 Disable
    
    SCU->IPCKENR1 = 0x0000E000;
    SCU->IPCKENR2 = 0x00000070;
    
    /* ADC配置，可以降低部分功耗 */
    ADC->TSREF |= (1 << 27);
    
    SCU->PCDADS |= 0x1 << 19; //Set Boot Pin to analog.

    SCU->RCHCR &=  (~SCU_RCHCR_RC4M_EN); //RC4M Disable.
    
    TKEY->ISR = 0xFFF;

    /*关闭SRAM未用空间*/
	//SCU->MEMCFG  |=(1<<16)| (2<<16)|(3<<16);

    /*RAM Retention 模式*/	
	SCU->STOPCFG |=(1<<28);
    
    EXTI->PDR = 0xFFFFFFFF; //清除EXTI中断标志位
    //RTC 域写使能
    SCU->STOPCFG |= SCU_STOPCFG_RTC_WE;
    RTC->SR = 0xFFFFFFFF;   //清除RTC中断标志位
    //RTC 域写禁止  
    SCU->STOPCFG &= (~SCU_STOPCFG_RTC_WE);
    
    /*Eflash 进入sleep模式 */
    EFC->CTRL |= 1<<12;
    
    SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk));   // Set SLEEPDEEP bit of Cortex System Control Register 
    
    SCU->STOPCFG &= (~BIT11);  // PDDS=0     

	/*---------------进入stop模式-----------*/
	/* Wait For Interrupt */   
    __WFI();
	
	/*---------------唤醒后设置-------------*/
	CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); 
	 	 
	/* 唤醒后，Eflash退出Sleep模式 */
	EFC->CTRL &= ~(1<<12);
	for(i = 0; i < 10 *5000; i++); //Elash退出Sleep最少延时10uS
    
    SCU->RCHCR |= SCU_RCHCR_RC4M_EN; //RC4M Enable.
    
	__set_PRIMASK(0);    // enable interrupt 
    /* Enable SysTick IRQ and SysTick Timer */ 
    SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
                   SysTick_CTRL_TICKINT_Msk   |
                   SysTick_CTRL_ENABLE_Msk;  
}



