#include "time_service.h"

extern "C"
{
    void SysTick_Handler( void ) //system timer interrupt
    {
        time_service::systemTime++;
    }
}

namespace time_service
{
    volatile uint64_t systemTime = 0; //one tick = 10 microseconds
    
    void startTime()
    {
        SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;
    }

    void stopTime()
    {
        SysTick->CTRL &= ~(SysTick_CTRL_ENABLE_Msk);
    }
    
    void delayms(uint64_t ms)
    {
        ms*=100;
        ms += systemTime;
        while(systemTime < ms);
    }
    
    void delayus(uint64_t us)
    {
        us /= 10;
        us += systemTime;
        while(systemTime < us);
    }
    
    uint32_t millis()
    {
        return systemTime/100;
    }
    
    uint64_t micros()
    {
        return systemTime*10;
    }

    void Init()
    {
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); //System timer clocking
        if( SysTick_Config(SystemCoreClock / 100000)) while(1); //frequency setup
    }
}
