/*********************************************************
*Copyright (C), 2017, Shanghai Eastsoft Microelectronics Co., Ltd
 * @文件名:  main.c
 * @作  者:  AE Team
 * @版  本:  V1.00
 * @日  期:  2022/07/25
 * @描  述:  sleep示例程序
          sleep示例程序，单独使用子板进行试验(需要断开子板上电源指示灯的限流电阻)，
          当供电电压低于3.6V进行休眠程序
          当供电电压高于4.1v退出休眠程序，PA23连续翻转
          休眠程序唤醒源如下：
            1.WDT唤醒后清狗，PB1端口电平翻转
            2.PINT唤醒，PB0端口电平翻转
            3.LVD唤醒系统软复位退出休眠函数
 * @note
 *          Change Logs:
 *          Date            Author          Notes
 *          25 July 2022    AE Team         change license to Apache-2.0
 *
 * Copyright (C) Shanghai Eastsoft Microelectronics Co. Ltd. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the License); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **********************************************************************************
 */


#include "main.h"

/* 睡眠标志 */
volatile uint8_t g_sleep_flag = 0;
volatile uint32_t timeCounter;

int main(void)
{
    HRC_Config(Enable, SCU_HRC_48M, Enable);    /* 配置HRC时钟频率 */
    SystemInit();
    DeviceClockAllEnable();

    /* LVD低电压检测初始化 */
    SCU_RegUnLock();
    SCU_LVDVS_4V1();
    SCU_LVDFLT_Enable();
    SCU_LVDIFS_Fall();                          /* LVDO高电平 */
    SCU_LVDIT_Enable();
    SCU_LVD_Enable();
    SCU_ClearPWRCFlagBit(SCU_PWRC_POR_LOST);    /* 清除上电复位标志 */
    SCU_RegLock();
    /* 须等待适当时间等待LVD采样 */
    timeCounter = 0xFFF;

    while (timeCounter--);

    /* LVD检测到电压低于4.1V则进入深度睡眠模式 */
    if (RESET != SCU_GetLVDFlagStatus(SCU_LVDFlag_Out))
    {
        deep_sleep();
    }

    /* 主循环初始化 */
    /* 修改LVD检测模式为上升沿检测，阈值3.6V并使能LVD中断 */
    SCU_RegUnLock();
    SCU_LVDVS_3V6();
    SCU_LVDIFS_Rise();
    NVIC_Init(NVIC_LVD_IRQn, NVIC_Priority_1, Enable);
    SCU_RegLock();

    /* 初始化systick、IWDT和GPIO管脚 */
    User_SysTickInit();
    WDTInit();
    OutPin_Init(GPIO_Pin_B1);
    OutPin_Init(GPIO_Pin_B0);

    /* 如果程序没有经历软件复位 */
    if (SCU_GetPWRCFlagStatus(SCU_PWRC_SOFTRSTF))
    {
        GPIO_ToggleBit(GPIO_Pin_B1);
        Delay_100us(10000);
        GPIO_ToggleBit(GPIO_Pin_B1);
        Delay_100us(10000);
    }

    while (1)
    {
        GPIO_ToggleBit(GPIO_Pin_B1);
        IWDT_Clear();
        Delay_100us(10);

        /* LVD中断检测到VDD电压低于3.6V，则复位进入休眠函数 */
        if (g_sleep_flag == 1)
        {
            NVIC_SystemReset();
        }
    }
}


/*************************END OF FILE**********************/
