#include "systick.h"


__IO uint64_t g_system_tick = 0;

void systick_config(void)
{
		/* setup systick timer for 1000Hz interrupts */
    if(SysTick_Config( system_core_clock / 1000U)) {
        /* capture error */
        while(1) {
        }
    }
    /* configure the systick handler priority */
    NVIC_SetPriority(SysTick_IRQn, 0x00U);
}



uint64_t get_system_tick(void)
{
		return g_system_tick;
}

void delay_us(uint32_t _us)
{
		uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;

    // 计算需要的时钟数 = 延迟微秒数 * 每微秒的时钟数
    ticks = _us * (SystemCoreClock / 1000000);

    // 获取当前的SysTick值
    told = SysTick->VAL;

    while (1)
    {
        // 重复刷新获取当前的SysTick值
        tnow = SysTick->VAL;

        if (tnow != told)
        {
            if (tnow < told)
                tcnt += told - tnow;
            else
                tcnt += SysTick->LOAD - tnow + told;

            told = tnow;

            // 如果达到了需要的时钟数，就退出循环
            if (tcnt >= ticks)
                break;
        }
    }
}

void delay_ms(uint32_t _ms) { delay_us(_ms * 500); }

