/*********************************************************
*Copyright (C), 2018, Shanghai Eastsoft Microelectronics Co., Ltd
*文件名:  ES_STL_clockstart.c
*作  者:  Eastsoft AE Team
*版  本:  V1.00
*日  期:  2018/06/21
*描  述:  CLASSB
*备  注:
          本软件仅供学习和演示使用，对用户直接引用代码所带来的风险或后果不承担任何法律责任。
**********************************************************/
/* Includes ------------------------------------------------------------------*/
#include "lib_config.h"
#include "ES_STL_param.h"
#include "ES_STLclassBvar.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

void delay(uint32_t  n)
{
    uint32_t i;

    for (i = 0; i < n; i++)
    {
        __NOP();
    }

}
/* Private functions ---------------------------------------------------------*/
/**
  * @brief  Start up the internal and external oscillators and verifies
  *   that clock source is within the expected range
  * @param :  None
  * @retval : ClockStatus_TEST_FAIL or ClockStatus_TEST_SUCCESSFUL
  */
ClockStatus STL_ClockStartUpTest(void)
{
    IWDT_InitStruType x;
    uint32_t ClockFrequency0;
    uint32_t ClockFrequency1;
    uint32_t ClockFrequency_temp;
    ClockStatus Result = ClockStatus_TEST_FAIL;


    CtrlFlowCnt += CLOCK_TEST_CALLEE;

    ClockFrequency0 = 0xFFFFFFul - SYSTICK_5MS_COUNT;//(0xFFFFFFul - SYSTICK_5MS_COUNT) 5ms后 sysclk在系统时钟下的理论值
    SysTick_Disable();      //使用时才开启

    IWDT_RegUnLock();
    x.WDT_Tms = 5;           //喂狗周期5*2ms
    x.WDT_IE = ENABLE;
    x.WDT_Rst = DISABLE;
    x.WDT_Clock = WDT_CLOCK_WDT;
    IWDT_Init(&x);
    NVIC_Init(NVIC_IWDT_IRQn, NVIC_Priority_0, DISABLE);
    IWDT_Enable();            //WDT需在解锁里面Enable
    SysTick_Enable();

    while (IWDT_GetFlagStatus() == RESET) ;  //WDT计数到喂狗周期的一半时产生中断标识

    ClockFrequency1 = SysTick->VAL;
    SysTick_Disable();
    IWDT_Disable();            //WDT需在解锁里面Disable
    IWDT_RegLock();

    if (SysTick->CTRL == 0x10000)   //Systick溢出则时钟故障
    {
        Result = ClockStatus_TEST_FAIL;
    }
    else if (ClockFrequency0 > ClockFrequency1)
    {
        ClockFrequency_temp = ClockFrequency0 - ClockFrequency1;

        if (ClockFrequency_temp < (SYSTICK_5MS_COUNT / 2))
        {
            Result = ClockStatus_TEST_SUCCESSFUL;
        }
    }
    else
    {
        ClockFrequency_temp = ClockFrequency1 - ClockFrequency0;

        if (ClockFrequency_temp < (SYSTICK_5MS_COUNT))
        {
            Result = ClockStatus_TEST_SUCCESSFUL;
        }
    }

    CtrlFlowCntInv -= CLOCK_TEST_CALLEE;

    return (Result);
}
/******************* (C) COPYRIGHT ESMicroelectronics *****END OF FILE****/
