#include "bsp_time.h"
u32 time_count4 = 0;
u16 time_count2 = 0;
u16 DelayMs = 0;
/*************系统时钟***********************/
void bsp_clk_init(void)
{
//#if(1)
//      #if AUTO_SWITCH
//          CLK->SWCR |= 0x02;
//          CLK->SWR = 0x04;
//          asm("NOP");
//          CLK->CKDIVR = 0x00;
//      #else
//          CLK->SWR = 0x04;
//          while((CLK->ECKCR & 0x02)==0);
//          CLK->SWCR |= 0x02;
//          while(!(CLK->SCSR & 0x04));
//          asm("NOP");
//          CLK->CKDIVR = SYSDIV;
//      #endif
//#else
//      CLK_SYSCLKSourceSwitchCmd(ENABLE);
//      CLK_SYSCLKSourceConfig(CLK_SYSCLKSource_HSE);
//      while(CLK_GetSYSCLKSource()!=CLK_SYSCLKSource_HSE);
//      asm("NOP");
//      CLK->CKDIVR = 0x00;
//#endif
//CLK->CSSR |= 0x01;
//asm("NOP");

  CLK_SYSCLKSourceSwitchCmd(ENABLE);
    CLK_SYSCLKSourceConfig(CLK_SYSCLKSource_HSI);
    /* 系统时钟分频*/
    CLK_SYSCLKDivConfig(CLK_SYSCLKDiv_1);//之前是CLK_SYSCLKDiv_1
    while (CLK_GetSYSCLKSource() != CLK_SYSCLKSource_HSI)
        {}
}

void bsp_time4_init(void)
{
      CLK_PeripheralClockConfig(CLK_Peripheral_TIM4,ENABLE);//CLK->PCKENR1 = 0x04;//使能定时器时钟
      TIM4->PSCR = TIMER4_DIV;//预分频
      TIM4->CR1 = 0x85;//工作模式
      TIM4->IER = 0x01;//定时器中断使能
      TIM4->ARR = TIMER4_ARR;//自动重载的值
}

void bsp_time2_init(void)
{
      CLK->PCKENR1 = 0x05;//使能定时器时钟
      TIM2->PSCR = 0x0E;//预分频
      TIM2->CR1 = 0x85;//工作模式
      TIM2->IER = 0x01;//定时器中断使能
      TIM2->CNTRH = 0x00;//自动重载的值
      TIM2->CNTRL = 0x00;
      TIM2->ARRH = 0x03;
      TIM2->ARRL = 0xE8;

}

void RtcConfig(void)
{

    CLK_LSICmd(ENABLE);
    while (CLK_GetFlagStatus(CLK_FLAG_LSIRDY) == RESET);
    CLK_PeripheralClockConfig(CLK_Peripheral_RTC, ENABLE);
    CLK_RTCClockConfig(CLK_RTCCLKSource_LSI, CLK_RTCCLKDiv_1);//38Khz
    RTC_WakeUpCmd(DISABLE);
    RTC_WakeUpClockConfig(RTC_WakeUpClock_RTCCLK_Div16);//16分频=2.375Khz
    //RTC_SetWakeUpCounter(8);//1s
    RTC_SetWakeUpCounter(2);
    RTC_ITConfig(RTC_IT_WUT, ENABLE);
    RTC_WakeUpCmd(ENABLE);

}

void bsp_delay_ms(u16 ms)
{
     time_count4 = ms;
     while(1)
     {
       if(time_count4==0)
       {
          break;
       }
     }
}

void bsp_delay_s(u16 s)
{
     time_count2 = s;
     while(1)
     {
       if(time_count2==0)
       {
          break;
       }
     }
}

void bsp_DelayMS(uint16_t ms)
{
    DelayMs = ms;
    while(DelayMs);
}

void SoftDelayMs(u32 ms)
{
  int i=0,j=0;
  while(ms--)
  {
    for(i=0;i<16;i++)
      for(j=0;j<1000;j++)
      {
        ;
      }
  }
}
