#include <pwm.h>


void PWM_GPIO_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    RCC_PB2PeriphClockCmd(RCC_PB2Periph_GPIOB, ENABLE);
//    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);    //打开管脚复用AFIO时钟
    RCC_PB1PeriphClockCmd(RCC_PB1Periph_TIM4, ENABLE);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;      //复用推挽输出
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOB, &GPIO_InitStructure);


    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
}

//定时器PWM输出配置
void PWM_TIM_Configuration(void)
{
    PWM_GPIO_Configuration();

    TIM_TimeBaseInitTypeDef TIM_BaseInitStructure;
    TIM_OCInitTypeDef TIM_OCInitStructure;

//    TIM_BaseInitStructure.TIM_Period = 1000 - 1;
//    TIM_BaseInitStructure.TIM_Prescaler = SystemCoreClock / 1000000 - 1;
    TIM_BaseInitStructure.TIM_Period = Period;
    TIM_BaseInitStructure.TIM_Prescaler = Prescaler;
    TIM_BaseInitStructure.TIM_ClockDivision = 0;
    TIM_BaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_BaseInitStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM4, &TIM_BaseInitStructure);

    TIM_ARRPreloadConfig(TIM4, ENABLE);

    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

    TIM_OCInitStructure.TIM_Pulse = 0;
    TIM_OC4Init(TIM4, &TIM_OCInitStructure);
    TIM_OC4PreloadConfig(TIM4, TIM_OCPreload_Enable);

    TIM_Cmd(TIM4, ENABLE);
    TIM_CtrlPWMOutputs(TIM4, ENABLE);
}

void Set_duty_ratio(float *duty_ratio)
{
    if (*duty_ratio < 0.5) {
        *duty_ratio = 0.5;
//        return;
    } else if (*duty_ratio > 0.9) {
        *duty_ratio = 0.9;
//        return;
    }

    uint16_t pulse = *duty_ratio * (Period + 1);
    TIM_SetCompare4(TIM4, pulse);
}
