#include "bsp/bsp.h"
#include "bsp/delay.h"


void task_ticks_enable(void)
{
	CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
	DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}

uint32_t task_ticks_abs(void)
{
	return DWT->CYCCNT;
}

uint32_t task_ticks_rel(uint32_t start)
{
	uint32_t ticks = DWT->CYCCNT;

	if (ticks >= start) {
		return ticks - start;
	}

	return 0xFFFFFFFF - start + ticks + 1;
}

void task_ticks_delay(uint32_t ticks)
{
	uint32_t start;

	start = task_ticks_abs();
	while (task_ticks_rel(start) < ticks);
}

void task_udelay(uint32_t delay)
{
	task_ticks_delay(delay * (SystemCoreClock / 1000000));
}


void delay_us(uint16_t cnt)
{
	task_udelay(cnt);
}

/*!
    \brief      delay a time in milliseconds
    \param[in]  count: count in milliseconds
    \param[out] none
    \retval     none
*/
void delay_ms(uint32_t count)
{
	task_udelay(1000 * count);
}

