stm32f103 pa15作为定时器2输出通道1输出pwm波形的代码
时间: 2024-01-05 11:03:18 浏览: 166
STM32F103C8T6定时器TIM4,双通道PWM输出
以下是使用STM32F103PA15作为定时器2输出通道1输出PWM波形的代码:
```c
#include "stm32f10x.h"
void TIM2_PWM_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
// 使能定时器2和GPIOA时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// 配置PA15为复用推挽输出模式
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置定时器2为自动重载模式
TIM_TimeBaseStructure.TIM_Period = 999; // PWM波形周期
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 定时器时钟频率为72MHz/72=1MHz
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置TIM2通道1为PWM模式1
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(TIM2, &TIM_OCInitStructure);
// 使能定时器2
TIM_Cmd(TIM2, ENABLE);
}
int main(void)
{
TIM2_PWM_Init();
while (1)
{
// 循环执行其他任务
}
}
```
阅读全文