stm32f103定时器5产生pwm程序
时间: 2023-05-20 18:03:13 浏览: 131
stm32的TIM3输出PWM
以下是一个基于 STM32F103 的定时器 5 产生 PWM 的程序:
#include "stm32f10x.h"
void TIM5_PWM_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
// 使能定时器 5 和 GPIOB 时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
// 配置 GPIOB.0 为复用推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 配置定时器 5 的时基
TIM_TimeBaseStructure.TIM_Period = 999; // PWM 周期为 1ms
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 定时器时钟为 72MHz / 72 = 1MHz
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);
// 配置定时器 5 的 PWM 输出通道
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 499; // PWM 占空比为 50%
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM5, &TIM_OCInitStructure);
// 使能定时器 5 的 PWM 输出通道
TIM_OC1PreloadConfig(TIM5, TIM_OCPreload_Enable);
// 启动定时器 5
TIM_Cmd(TIM5, ENABLE);
}
int main(void)
{
TIM5_PWM_Init();
while (1);
return 0;
}
阅读全文