基于stm32f103zet6控制两路pwm电机代码
时间: 2023-07-04 15:21:29 浏览: 165
stm32f103 控制PWM输出
5星 · 资源好评率100%
以下是基于STM32F103ZET6控制两路PWM电机的示例代码,其中使用了TIM2和TIM3模块来控制两路PWM信号输出:
```c
#include "stm32f10x.h"
void PWM_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// 配置PA0和PA1为复用推挽输出,用于PWM输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void PWM_TIM_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 | RCC_APB1Periph_TIM3 , ENABLE);
// PWM频率为10kHz
uint16_t PrescalerValue = (uint16_t) (SystemCoreClock / 10000) - 1;
// 配置TIM2为PWM输出模式
TIM_TimeBaseStructure.TIM_Period = 999;
TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &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(TIM2, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);
// 配置TIM3为PWM输出模式
TIM_TimeBaseStructure.TIM_Period = 999;
TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
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);
// 启动TIM2和TIM3
TIM_Cmd(TIM2, ENABLE);
TIM_Cmd(TIM3, ENABLE);
}
int main(void)
{
// 初始化PWM GPIO口
PWM_GPIO_Config();
// 初始化PWM TIM模块
PWM_TIM_Config();
while(1)
{
// 控制电机1的PWM占空比为50%
TIM_SetCompare1(TIM2, 500);
// 控制电机2的PWM占空比为75%
TIM_SetCompare1(TIM3, 750);
}
}
```
在上述代码中,使用`PWM_GPIO_Config()`函数配置了PA0和PA1为复用推挽输出,用于PWM输出;`PWM_TIM_Config()`函数初始化了TIM2和TIM3模块,并设置了PWM频率为10kHz;在`main()`函数中,通过调用`TIM_SetCompare1()`函数来控制两路PWM信号的占空比,从而控制电机转速。
阅读全文