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


#define PERIOD_VALUE        1000
#define PULSE1_VALUE        100
#define PULSE2_VALUE        100


static TIM_HandleTypeDef   TimHandle;
static TIM_OC_InitTypeDef  sConfig;



//
void tim_pwm_out_init(void)
{
    GPIO_InitTypeDef   GPIO_InitStruct;
    
    uint32_t uhPrescalerValue = 0;
    uhPrescalerValue = (uint32_t)(SystemCoreClock / 16000000) - 1;
    
    __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 | GPIO_PIN_10;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    
    TimHandle.Instance = TIM1;
    TimHandle.Init.Prescaler         = uhPrescalerValue;
    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 = PULSE1_VALUE;
    HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, TIM_CHANNEL_2);
    
    sConfig.Pulse = PULSE2_VALUE;
    HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, TIM_CHANNEL_3);
    
    HAL_TIM_PWM_Start(&TimHandle, TIM_CHANNEL_2);
    HAL_TIM_PWM_Start(&TimHandle, TIM_CHANNEL_3);
}