void pwm_init(PWMCH_enum pwmch, uint32 freq, uint32 duty, uint16_t TIM_OCPreload_Enable_Disable) { TIM_OCInitTypeDef TIM_OCInitStructure; uint16 match_temp; //占空比值 uint16 period_temp; //周期值 uint16 freq_div = 0; //分频值 pwm_gpio_init(pwmch); //PWM引脚初始化 /* 获取
时间: 2024-04-23 17:22:42 浏览: 136
opcenum.zip_ATL event_C Builder_c++builder enum_opc_opcenum
该函数是一个用于STM32定时器PWM模式初始化的函数。具体实现步骤如下:
1. 定义一个TIM_OCInitTypeDef类型的结构体变量TIM_OCInitStructure,用于配置定时器的输出比较通道(Output Compare Channel)。
2. 定义两个变量match_temp和period_temp,分别用于存储PWM的占空比和周期值。
3. 定义一个变量freq_div,用于保存定时器的分频值。
4. 调用pwm_gpio_init函数,对PWM引脚进行初始化。
5. 根据输入参数pwmch,选择对应的定时器,并配置定时器的时钟源和分频值。
6. 根据输入参数freq,计算定时器的周期值和占空比的计数值。
7. 配置TIM_OCInitStructure结构体,设置PWM输出模式、占空比和预装载模式。
8. 启动定时器,并使能PWM输出。
以下是具体的代码实现:
```c
void pwm_init(PWMCH_enum pwmch, uint32 freq, uint32 duty, uint16_t TIM_OCPreload_Enable_Disable)
{
TIM_OCInitTypeDef TIM_OCInitStructure;
uint16_t match_temp;
uint16_t period_temp;
uint16_t freq_div = 0;
pwm_gpio_init(pwmch);
TIM_TypeDef *TIMx = pwmch_to_tim(pwmch);
if (TIMx == TIM1 || TIMx == TIM8) {
RCC_APB2PeriphClockCmd(pwmch_to_rcc(pwmch), ENABLE);
} else {
RCC_APB1PeriphClockCmd(pwmch_to_rcc(pwmch), ENABLE);
}
freq_div = (SystemCoreClock / 2) / freq;
period_temp = freq_div - 1;
match_temp = (period_temp + 1) * duty / 100 - 1;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period = period_temp;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIMx, &TIM_TimeBaseStructure);
TIM_OCStructInit(&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = match_temp;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
TIM_OCInitStructure.TIM_OCIdleness = TIM_OCIdleness_Reset;
TIM_OCInitStructure.TIM_OCNPIdleState = TIM_OCNPIdleState_Reset;
TIM_OCInitStructure.TIM_OCPreload = TIM_OCPreload_Enable_Disable;
TIM_OC1Init(TIMx, &TIM_OCInitStructure);
TIM_Cmd(TIMx, ENABLE);
TIM_CCxCmd(TIMx, pwmch_to_channel(pwmch), TIM_CCx_Enable);
}
```
在上述代码中,我们首先调用pwm_gpio_init函数,对PWM引脚进行初始化。然后根据输入参数pwmch,选择对应的定时器,并配置定时器的时钟源和分频值。接着,根据输入参数freq,计算定时器的周期值和占空比的计数值,并配置TIM_OCInitStructure结构体,设置PWM输出模式、占空比和预装载模式。最后启动定时器,并使能PWM输出。
阅读全文