#include "stddef.h"
#include "BAT32A279.h"
#include "core_cm0plus.h"
#include "RTE_Tick_Timer.h"

#define   RTE_TICK_TIMER_CLK_SRC_FREQ      (64000000UL)
#define   RTE_SysTick_LOAD_RELOAD_Msk      0xFFFFFFUL

RTE_Tick_Timer_Call_Back_ptr_t   g_pfnRTETickTimerCallBackFunc = NULL;

uint8_t  u8Value_us =0;

 
void RTE_Tick_Timer_Start(uint32_t u32Interval, RTE_Tick_Timer_Call_Back_ptr_t pfnCallBack)
{
	if ((u32Interval - 1UL) > RTE_SysTick_LOAD_RELOAD_Msk)
 	{
   		u32Interval = 1UL;                                                    /* Reload value impossible */
 	}
	
	if(u32Interval < 1UL)
	{
		u32Interval = 1UL; 
	}

	u8Value_us = RTE_TICK_TIMER_CLK_SRC_FREQ/1000000;
    SysTick->LOAD  = u32Interval * u8Value_us;
	NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL);
	SysTick->VAL   = 0UL;
	SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk;
    
    g_pfnRTETickTimerCallBackFunc = pfnCallBack;
}

void RTE_Tick_Timer_Stop(void)
{
    NVIC_DisableIRQ(SysTick_IRQn);
    SysTick->CTRL  = 0UL;
    SysTick->VAL   = 0UL;
}

void RTE_SysTick_Handler(void)
{
	if (g_pfnRTETickTimerCallBackFunc != NULL)
	{
		g_pfnRTETickTimerCallBackFunc();
	}
	Sys_Exact_50us_Tasks();
}
