/*****************************************************************************
* File Name          : Systick_For_Timeout.c
* Author             : Crystal Su
* Version            : V1.0.0.0
* Date               : Feb 06, 2020
* Description        : 
******************************************************************************/   


#include "Systick_For_Timeout.h"

// variables
volatile uint16_t  i_Timeout_Count ;
volatile uint32_t  uwTick;

uint16_t get_Timeout_Count()
{
	return i_Timeout_Count;
}

void Time_Handler()
{
	//HT_GPIOB->DOUTR ^= GPIO_PIN_0;
	uwTick ++;
	if ( i_Timeout_Count > 0 )
	{
		i_Timeout_Count -- ;	
	}
}

uint8_t Systick_1ms_Init( void )
{
  SYSTICK_ClockSourceConfig(SYSTICK_SRC_STCLK);       	// Default : CK_SYS/8
  SYSTICK_SetReloadValue(SystemCoreClock / 8 / 1000); 				// (CK_SYS/8/1000) = 1ms on chip
  SYSTICK_IntConfig(ENABLE);                          	// Enable SYSTICK Interrupt
	
  /* Enable the SysTick Counter */
  SYSTICK_CounterCmd(SYSTICK_COUNTER_CLEAR);
  SYSTICK_CounterCmd(SYSTICK_COUNTER_ENABLE);
	return 1 ;
}

void Systick_Timeout_Start( uint16_t Count_times )
{
	i_Timeout_Count = Count_times ;

	// Clear SysTick Counter
  //SYSTICK_CounterCmd(SYSTICK_COUNTER_CLEAR);
  //SYSTICK_CounterCmd(SYSTICK_COUNTER_ENABLE);
}

void Systick_Timeout_Stop( void )
{
	// Disable SysTick Counter
  //SYSTICK_CounterCmd(SYSTICK_COUNTER_DISABLE);
}

uint8_t TimeOut_Check( void )
{		
	if( i_Timeout_Count > 0 )
	{
		return  0 ; 
	}
	else
	{
		return  1 ;
	}
}

uint32_t Get_TickCount()
{
	return uwTick;
}

void Delay(uint32_t Delay)
{
  uint32_t tickstart = Get_TickCount();
  uint32_t wait = Delay;

  /* Add a freq to guarantee minimum wait */
  if (wait < HAL_MAX_DELAY)
  {
    wait ++;
  }

  while ((Get_TickCount() - tickstart) < wait)
  {
  }
}
