stm32pwm输出方波的代码
时间: 2023-11-12 09:05:21 浏览: 195
以下是 STM32 PWM 输出方波的代码示例:
```
#include "stm32f4xx.h"
#define PWM_FREQ 4000 // PWM 频率
#define PWM_PERIOD 840 // PWM 周期
void init_pwm_gpio(void)
{
// 配置 PWM 引脚的GPIO
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; // PWM 输出引脚
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; // 复用模式
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 将 PWM 引脚绑定到 TIM10 的通道1上
GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_TIM10);
}
void init_pwm_timer(void)
{
// 配置 TIM10
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM10, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Prescaler = SystemCoreClock / PWM_FREQ / PWM_PERIOD - 1; // 定时器分频
TIM_TimeBaseStructure.TIM_Period = PWM_PERIOD - 1; // 定时器周期
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM10, &TIM_TimeBaseStructure);
// 配置 TIM10 的通道1 为 PWM 模式
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM10, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM10, TIM_OCPreload_Enable);
TIM_Cmd(TIM10, ENABLE); // 启动TIM10
}
int main(void)
{
init_pwm_gpio();
init_pwm_timer();
while(1);
return 0;
}
```
阅读全文