STM32F103C8T6定时器3输出4路PWM波标准库
时间: 2024-02-20 15:52:14 浏览: 89
STM32-控制PA3TIM2-CH4输出PWM值_stm32f103c8t6_STM32PA3PWM_PWM频率stm32_P
5星 · 资源好评率100%
以下是STM32F103C8T6定时器3输出4路PWM波标准库的代码:
```c
#include "stm32f10x.h"
void TIM3_PWM_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
//使能GPIOB和TIM3的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
//将PB0、PB1、PB4、PB5配置为复用推挽输出模式
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_4 | GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//定时器TIM3初始化
TIM_TimeBaseStructure.TIM_Period = 1999; //计数器自动重装值
TIM_TimeBaseStructure.TIM_Prescaler = 71; //定时器分频
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
//PWM模式初始化
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //PWM模式1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
//CH1 PWM输出初始化
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
//CH2 PWM输出初始化
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
//CH3 PWM输出初始化
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
//CH4 PWM输出初始化
TIM_OC4Init(TIM3, &TIM_OCInitStructure);
TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
//启动TIM3
TIM_Cmd(TIM3, ENABLE);
}
```
注:以上代码中,定时器TIM3的频率为84MHz/72=1.1667MHz,PWM波的频率为1.1667MHz/2000=583.3Hz。对于每个PWM通道,占空比范围为0-1999,对应的占空比范围为0%-100%。在使用时,可以通过修改TIM_OCInitStructure.TIM_Pulse的值来改变占空比。
阅读全文