#ifdef __cplusplus
extern "C" {
#endif 

#include "delay.h"

float count_time = 0;
float count_us = 0;
float count_ms = 0;
float reload = 0;


void System_TimerInit(void)
{
    SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);//clear bit2, and using external clock     HCK/8
    count_us=SystemCoreClock / 8000000;
    count_ms=(uint16_t)count_us * 1000;
    reload = 16777215;

    SysTick->CTRL|=SysTick_CTRL_TICKINT_Msk;     //enable SYSTICK interrupt
    SysTick->LOAD=reload; 						 //enter interrupt every 1/delay_ostickspersec second
    SysTick->VAL = reload;
    SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk;   	 //enable SYSTICK
}


void SysTick_Handler(void)
{
    count_time++;
    if(count_time >= 0xffffffff)
    {
        count_time=0;
    }
}

float getSystemTime(void)
{
    float count , time;
    count = (float)( (reload + 1 - SysTick->VAL) + (float)(reload + 1) * count_time);
    time = count/count_us;
    return time;
}

float getDeltaTime(void)
{
    static float lasttime;
    float temp1,temp2;
    temp1 = getSystemTime();
    temp2 = temp1 - lasttime;
    if(temp2 < 0)
    {
        temp2 = ( ( (float)(reload + 1) * (float)0xffffffff) / count_us) - lasttime  + temp1;
    }
    lasttime = temp1;
    return temp2;
}

void delay_us(unsigned short int t)
{
    int i;
    for( i=0;i<t;i++)
    {
        int a=9;
        while(a--) ;
    }   
}

void delay_ms(unsigned short int t)
{
    int i;
    for( i=0;i<t;i++)
    {
        int a=10300;
        while(a--) ;
    }
}

#ifdef __cplusplus
}
#endif 
