#include "stm32f0xx_hal.h"
#include "pwm_out.h"
#include <stdio.h>

#define PWM_OUT_TIM_FREQ    1000000
#define PERIOD_VALUE        20000

#define IDLE_PULSE          1160    // Начальное значение PWM до нажатий


static TIM_HandleTypeDef   TimHandle;
static TIM_OC_InitTypeDef  sConfig;

static uint16_t prescaler;


//
void tim_pwm_out_init(void)
{
    GPIO_InitTypeDef   GPIO_InitStruct;
    
    
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_TIM1_CLK_ENABLE();
    
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF2_TIM1;
    GPIO_InitStruct.Pin = GPIO_PIN_9;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    
    prescaler = HAL_RCC_GetHCLKFreq()/PWM_OUT_TIM_FREQ - 1;
    
    TimHandle.Instance = TIM1;
    TimHandle.Init.Prescaler         = prescaler;
    TimHandle.Init.Period            = PERIOD_VALUE;
    TimHandle.Init.ClockDivision     = 0;
    TimHandle.Init.CounterMode       = TIM_COUNTERMODE_UP;
    TimHandle.Init.RepetitionCounter = 0;
    TimHandle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
    HAL_TIM_PWM_Init(&TimHandle);
    
    sConfig.OCMode       = TIM_OCMODE_PWM1;
    sConfig.OCPolarity   = TIM_OCPOLARITY_HIGH;
    sConfig.OCFastMode   = TIM_OCFAST_DISABLE;
    sConfig.OCNPolarity  = TIM_OCNPOLARITY_HIGH;
    sConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET;
    
    sConfig.OCIdleState  = TIM_OCIDLESTATE_RESET;
    
    sConfig.Pulse = IDLE_PULSE;
    HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, TIM_CHANNEL_2);
    
    HAL_TIM_PWM_Start(&TimHandle, TIM_CHANNEL_2);
}

//
void tim_pwm_out_set_pulse(pwm_out_ch channel, uint16_t pulse)
{
    switch (channel)
    {
        case PWM_OUT_CH_1: 
            TIM1->CCR2 = pulse;
        break;
        
        default : break;
    }  
}

//
void tim_pwm_pulse_idle(void)
{
    TIM1->CCR2 = IDLE_PULSE;
}