
/******************************************************************************
*@file  : app.c
*@brief : application
******************************************************************************/

#include "app.h" 

volatile uint32_t g_arr_complete;
volatile uint32_t g_curr_tick;

/******************************************************************************
*@brief : app test
*@param : none
*@return: none
******************************************************************************/
void APP_Test(void)
{
    uint32_t period;
    uint32_t prev_tick;
    uint32_t freq;
    GPIO_InitTypeDef  GPIO_InitStruct = {0};
    LPTIM_InitTypeDef LPTIM_InitStruct = {0};
    
	printfS("SPL LPTIM Demo: Counter\r\n");
	printfS("\r\n");
    
	BSP_LED_Init();
    BSP_LED_On();
    DelayMs(500);
    BSP_LED_Off();
    DelayMs(500);
    BSP_LED_On();
    DelayMs(500);
    BSP_LED_Off();
    DelayMs(500);
    
    NVIC_ClearPendingIRQ(LPTIM1_IRQn);
    NVIC_SetPriority(LPTIM1_IRQn, 0x00);
    NVIC_EnableIRQ(LPTIM1_IRQn);
    
    LPTIM_DeInit(LPTIM1);
    __RCC_LPTIM1_CLK_ENABLE();
    LPTIM_Reset(LPTIM1);
    
    LPTIM_InitStruct.ClockSource = LPTIM_CLOCKSOURCE_INTERNAL_PCLK;
    LPTIM_InitStruct.Prescaler = LPTIM_CLOCKPRESCALER_DIV128;
    LPTIM_InitStruct.Waveform = LPTIM_WAVEFORM_PWM_ONEPULSE;
    LPTIM_InitStruct.OutputPolarity = LPTIM_OUTPUTPOLARITY_HIGH;
    
    LPTIM_Init(LPTIM1, &LPTIM_InitStruct);
    
    LPTIM_SelectSoftwareStart(LPTIM1);
    LPTIM_ConfigUpdate(LPTIM1, LPTIM_UPDATE_IMMEDIATE);
    LPTIM_SelectCounterMode(LPTIM1, DISABLE);
    
    LPTIM_ClearFlag(LPTIM1, LPTIM_FLAG_ARRM);
    LPTIM_ITConfig(LPTIM1, LPTIM_IT_ARRM, ENABLE);
    
    LPTIM_Cmd(LPTIM1, ENABLE);
    
    period = 100;
    freq = ((RCC_GetPCLK1Freq() * period) / 128000) - 1;
    
    LPTIM_ClearFlag(LPTIM1, LPTIM_FLAG_CMPOK);
    LPTIM_SetCompareValue(LPTIM1, freq >> 1);
    while (LPTIM_GetFlagStatus(LPTIM1, LPTIM_FLAG_CMPOK) == RESET);
    
    LPTIM_ClearFlag(LPTIM1, LPTIM_FLAG_ARROK);
    LPTIM_SetAutoreloadValue(LPTIM1, freq);
    while (LPTIM_GetFlagStatus(LPTIM1, LPTIM_FLAG_ARROK) == RESET);
    
    g_arr_complete = 0;
    g_curr_tick = 0;
    prev_tick = SysTick_Get();
    LPTIM_SelectOperatingMode(LPTIM1, LPTIM_MODE_CONTINUOUS);
    
    printfS("ARR period: %u ms.\r\n", period);
    printfS("\r\n");
    
    while(1)
    {
        while (g_arr_complete == 0);
        
        g_arr_complete = 0;
        BSP_LED_Toggle();
        
        printfS("The current TICK is %u ms, and the TICK interval is %u ms.\r\n", g_curr_tick, g_curr_tick - prev_tick);
        prev_tick = g_curr_tick;
    };
}

void lptim1_irq_handle(void)
{
    g_curr_tick = SysTick_Get();
    if (LPTIM_GetITStatus(LPTIM1, LPTIM_IT_ARRM))
    {
        LPTIM_ClearFlag(LPTIM1, LPTIM_FLAG_ARRM);
        g_arr_complete = 1;
    }
    if (LPTIM_GetITStatus(LPTIM1, LPTIM_IT_ARRM))
    {
        LPTIM_ClearFlag(LPTIM1, LPTIM_FLAG_ARRM);
    }
}




