stm32f103 P3P4P5P6P7P8P9口输出PWM,代码
时间: 2023-11-20 11:40:42 浏览: 82
以下是在STM32F103芯片上使用定时器输出PWM信号的示例代码,使用了P3、P4、P5、P6、P7、P8、P9端口:
```c
#include "stm32f10x.h"
void GPIO_Configuration(void);
void TIM_Configuration(void);
int main(void)
{
GPIO_Configuration();
TIM_Configuration();
while (1)
{
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 1999; // 1 kHz PWM frequency
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1; // 72 MHz / 72 = 1 MHz
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_OC4Init(TIM3, &TIM_OCInitStructure);
TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OC5Init(TIM3, &TIM_OCInitStructure);
TIM_OC5PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OC6Init(TIM3, &TIM_OCInitStructure);
TIM_OC6PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_Cmd(TIM3, ENABLE);
}
```
这段代码使用了定时器 TIM3 来输出 PWM 信号,其频率为 1 kHz,占空比可以通过修改 `TIM_OCInitStructure.TIM_Pulse` 来调整。同时,定时器的时钟源使用的是 APB1 总线,其时钟频率为 72 MHz,因此需要将 `TIM_TimeBaseStructure.TIM_Prescaler` 设为 72-1,以得到 1 MHz 的时钟信号。输出端口使用的是 GPIOB 3~9 口,使用复用功能输出 PWM 信号。
阅读全文