/**************************************************************************//**
 * @file     timer_common.c
 * @version  V1.0
 * $Date:    19/10/30 16:47 $
 * @brief    Common source file for Timer test.
 *
 * @note
 * Copyright (C) 2019 Panchip Technology Corp. All rights reserved.
 *
 ******************************************************************************/
#include <ctype.h>
#include "pan271x.h"
#include "timer_common.h"

volatile uint32_t tmr_int_trigger_cnt = 0;
volatile uint32_t tmr_cap_int_cnt = 0;
volatile uint32_t cap_buf[20];

void TIMER_HandleProc(TIMER_T* TIMERx)
{
	if (TIMER_GetCapFlag(TIMERx))
    {
        // Clear Timer interrupt flag
        TIMER_ClearTFFlag(TIMERx, TIMER_CTL_CAPTURE_FLAG_Msk);
		cap_buf[tmr_cap_int_cnt++] = TIMER_GetCaptureCount(TGT_TIMER);
    }

    if (TIMER_GetTFFlag(TIMERx))
    {
        // Clear Timer interrupt flag
        TIMER_ClearTFFlag(TIMERx, TIMER_CTL_TIMER_FLAG_Msk);
        tmr_int_trigger_cnt++;
		SYS_TEST("CNT\n");
		SYS_delay_10nop(1000);
    }
}

void TMR0_IRQHandler(void)
{
    TIMER_HandleProc(TIMER0);
}


void TIMER_TestModuleInit(void)
{
    // Enable Clock
    CLK_APB1PeriphClockCmd(CLK_APB1Periph_TMR0, ENABLE);    //Target TMR

    CLK_APB1PeriphClockCmd(CLK_APB1Periph_PWM0_CH45, ENABLE);
    SYS_SET_MFP(P1, 2, PWM_CH4);
}

void TIMER_DelayMs(TIMER_T *timer, uint32_t u32Ms)
{
    uint32_t u32Clk = CLK_GetPeripheralFreq(timer);
	
    uint32_t u32Prescale = 0xFF;
    uint32_t u32Cmp;

    // Set timer clock source to APB
    CLK_SetTmrClkSrc(NULL);

    // Get the largest divisor (u32Prescale+1) which can evenly divide u32Clk
    while(u32Clk % (u32Prescale+1) || (u32Clk / (u32Prescale+1) % 1000u))
    {
        u32Prescale--;
    }

    u32Cmp = u32Clk / (u32Prescale + 1) / 1000u * u32Ms;

    TIMER_SetCmpValue(timer, u32Cmp);

    TIMER_Start(timer);

    while(!(timer->TIMER_CTL & TIMER_CTL_TIMER_FLAG_Msk));
	TIMER_ClearTFFlag(timer, TIMER_CTL_TIMER_FLAG_Msk);
}
