/********************************************************************************
 * @file    STOP_IDLE_WakeUp_Example.c
 * @author  SOC AE Team
 * @version V1.1
 * @date    2025-06-27
 * @brief   BTM/INT将IC从STOP/IDLE模式唤醒
 *         （STOP模式：IC_Mode=0   IDLE模式：IC_Mode=1）
 *         （BTM唤醒：WakeUp_Mode=0   INT唤醒：WakeUp_Mode=1）
 *
 *******************************************************************************/
#include "sc32_conf.h"
#include "Function_Init.h"
#include "stdio.h"
#include "SC_Init.h"

/* 选择STOP/IDLE模式（STOP模式：IC_Mode=0   IDLE模式：IC_Mode=1） */
#define IC_Mode 1

/* 选择唤醒外设（BTM唤醒：WakeUp_Mode=0   INT唤醒：WakeUp_Mode=1） */
#define WakeUp_Mode 0

void STOP_IDLE_WakeUp_Function(void)
{
  GPIO_InitTypeDef GPIO_InitStruct; //定义GPIO初始化结构体变量
  /* PA10设置为推挽输出 */
  GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT_PP;
  GPIO_Init(GPIOA, &GPIO_InitStruct);
	
#if (WakeUp_Mode == 0)
  /* BTM配置 */
  RCC_Unlock(0xFF);
  RCC_LIRCCmd(ENABLE);//使能LIRC
#if defined(SC32f10xx)|| defined(SC32f12xx)
  RCC_APB2Cmd(ENABLE);//使能BTM时钟

#endif	
  BTM_FSConfig(BTM,BTM_FreqSelect_500MS);//BTM定时时间设置
  BTM_ITConfig(BTM,BTM_IT_INT,ENABLE);//使能BTM中断
  NVIC_EnableIRQ(BTM_IRQn);
  
  BTM_Cmd(BTM,ENABLE);//使能BTM外设
#elif(WakeUp_Mode == 1)
  INT_InitTypeDef INT_InitStruct; //定义INT初始化结构体变量
  
  //PA0设置为上升沿中断
  INT_InitStruct.INT_Channel = INT_Channel_0;
  INT_InitStruct.INT_INTSEL = INT_INTSEL_PA;
  INT_InitStruct.INT_Trigger = INT_Trigger_Rising;
  INT_Init(&INT_InitStruct);
  
  /* 开启对应的中断 */
  INT_ITConfig(INT_Channel_0, INT_IT_Rising, ENABLE);
  NVIC_EnableIRQ(INT0_IRQn);
	
#endif
  while(1)
  {
#if (IC_Mode == 0)
    printf("Enter STOP mode!\r\n");
    PWR_EnterSTOPMode(PWR_STOPEntry_WFI);//进入STOP模式
    SC_Init(); //重新初始化时钟
    
#elif(IC_Mode == 1)
    printf("Enter IDLE mode!\r\n");
    PWR_EnterIDLEMode(PWR_IDLEEntry_WFI);//进入IDLE模式	
#endif
    
    PA_OT(10); //PA10翻转
    
#if (WakeUp_Mode == 0)
    printf("Woken up by BTM interrupt!\r\n");
#elif(WakeUp_Mode == 1)
    printf("Woken up by INT interrupt!\r\n");
#endif
  }
}

//BTM中断
void BTM_WakeUp_BTMHandler(void)
{
  /* 判断BTM中断是否置起 */
  if(BTM_GetFlagStatus(BTM,BTM_FLAG_IF) == SET)
  {
    BTM_ClearFlag(BTM,BTM_FLAG_IF);	//清除BTM中断标志
  }
}

//INT中断
void INT_WakeUp_INT0Handler(void)
{
  if(INT_GetFlagStatus(INT_Channel_0, INT_Flag_Rising)) //判断INT0标志位
  {
      INT_ClearFlag(INT_Channel_0);
  }
}

