GDF103RC使用TIM1输出三路pwm
时间: 2023-11-11 08:06:14 浏览: 79
GDF103RC的TIM1可以输出最多4路PWM信号,可以使用以下代码实现三路PWM输出:
```c
#include "stm32f10x.h"
void TIM1_PWM_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO | RCC_APB2Periph_TIM1, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 999; // PWM周期为1000
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 分频系数为72
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0; // 初始占空比为0
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC2Init(TIM1, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC3Init(TIM1, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_Cmd(TIM1, ENABLE);
}
int main(void)
{
TIM1_PWM_Init();
while(1) {
TIM_SetCompare1(TIM1, 500); // 设置通道1的占空比为50%
TIM_SetCompare2(TIM1, 250); // 设置通道2的占空比为25%
TIM_SetCompare3(TIM1, 750); // 设置通道3的占空比为75%
delay_ms(1000);
}
}
```
其中,使用了GPIOA的8、9、10三个引脚作为PWM输出引脚,TIM1的时钟频率为72MHz,分频系数为72,因此PWM的周期为1ms,可根据需要修改。在main函数中,使用TIM_SetCompare函数设置每个PWM通道的占空比,实现三路PWM输出。
阅读全文