#include "stddef.h"
#include "BAT32A239.h"
#include "core_cm0plus.h"
#include "RTE_Tick_Timer.h"
#include "System\Sys_Scheduler.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 SysTick_Handler(void);
 
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 = (uint8_t)(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 SysTick_Handler(void)
{
//	SysTick->CTRL;
//	
	if (g_pfnRTETickTimerCallBackFunc != NULL)
	{
		g_pfnRTETickTimerCallBackFunc();
	}
	Sys_Exact_50us_Tasks();
}
