#include "stm32f0xx_hal.h"
#include "tim.h"
#include "led.h"


TIM_HandleTypeDef    Tim16Handle;
TIM_HandleTypeDef    Tim17Handle;


// TIM17 - индикация нажатия курка
// TIM16 - инфракрасный диод
void tim_init(void)
{
    __HAL_RCC_TIM16_CLK_ENABLE();
    __HAL_RCC_TIM17_CLK_ENABLE();  
    
    Tim16Handle.Instance               = TIM16;
    Tim16Handle.Init.Period            = 10000 - 1;
    Tim16Handle.Init.Prescaler         = 4800 - 1;
    Tim16Handle.Init.ClockDivision     = 0;
    Tim16Handle.Init.CounterMode       = TIM_COUNTERMODE_UP;
    Tim16Handle.Init.RepetitionCounter = 0;
    Tim16Handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
    HAL_TIM_Base_Init(&Tim16Handle);
    
    HAL_NVIC_SetPriority(TIM16_IRQn, 2, 0);
 
    HAL_NVIC_EnableIRQ(TIM16_IRQn);
    
    
    Tim17Handle.Instance               = TIM17;
    Tim17Handle.Init.Period            = 2000 - 1;
    Tim17Handle.Init.Prescaler         = 4800 - 1;
    Tim17Handle.Init.ClockDivision     = 0;
    Tim17Handle.Init.CounterMode       = TIM_COUNTERMODE_UP;
    Tim17Handle.Init.RepetitionCounter = 0;
    Tim17Handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
    HAL_TIM_Base_Init(&Tim17Handle);
    
    HAL_NVIC_SetPriority(TIM17_IRQn, 2, 0);
 
    HAL_NVIC_EnableIRQ(TIM17_IRQn);
}


//
void tim_signal_start(void)
{
    __HAL_TIM_CLEAR_IT(&Tim17Handle, TIM_IT_UPDATE);
    HAL_TIM_Base_Start_IT(&Tim17Handle);
}


//
void tim_inf_set_time(uint16_t time)
{
    __HAL_TIM_CLEAR_IT(&Tim16Handle, TIM_IT_UPDATE);
    TIM16->ARR = time;
    HAL_TIM_Base_Start_IT(&Tim16Handle);
}


//
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if (htim->Instance == TIM16) 
    {
        HAL_TIM_Base_Stop_IT(&Tim16Handle);
        led_inf_off();
    } 
    else if (htim->Instance == TIM17) 
    {
        HAL_TIM_Base_Stop_IT(&Tim17Handle);
        led_signal_off();
    }
}


//
void TIM16_IRQHandler(void)
{
    HAL_TIM_IRQHandler(&Tim16Handle);
}


//
void TIM17_IRQHandler(void)
{
    HAL_TIM_IRQHandler(&Tim17Handle);
}


#if 0
void TIM1_BRK_UP_TRG_COM_IRQHandler(void)
{
    HAL_TIM_IRQHandler(&TimHandle);
}
#endif