下面是一个使用STM32驱动电机的简单示例代码:
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_tim.h"
#define MOTOR_PWM_PIN GPIO_Pin_9
#define MOTOR_PWM_PORT GPIOA
#define MOTOR_DIR_PIN GPIO_Pin_10
#define MOTOR_DIR_PORT GPIOA
#define MOTOR_TIM TIM1
#define MOTOR_TIM_CLK RCC_APB2Periph_TIM1
#define MOTOR_TIM_CH TIM_OCMode_PWM1
#define MOTOR_TIM_PRESC 84
#define MOTOR_TIM_PERIOD 1000
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = MOTOR_PWM_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ;
GPIO_Init(MOTOR_PWM_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = MOTOR_DIR_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_Init(MOTOR_DIR_PORT, &GPIO_InitStructure);
GPIO_PinAFConfig(MOTOR_PWM_PORT, GPIO_PinSource9, GPIO_AF_TIM1);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(MOTOR_TIM_CLK, ENABLE);
TIM_TimeBaseStructure.TIM_Prescaler = MOTOR_TIM_PRESC - 1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = MOTOR_TIM_PERIOD - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(MOTOR_TIM, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = MOTOR_TIM_CH;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Disable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset;
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Reset;
TIM_OC1Init(MOTOR_TIM, &TIM_OCInitStructure);
TIM_Cmd(MOTOR_TIM, ENABLE);
}
void Motor_Drive(int speed, int direction)
{
if (direction) {
GPIO_SetBits(MOTOR_DIR_PORT, MOTOR_DIR_PIN);
} else {
GPIO_ResetBits(MOTOR_DIR_PORT, MOTOR_DIR_PIN);
}
TIM_SetCompare1(MOTOR_TIM, speed);
}
int main(void)
{
GPIO_Configuration();
TIM_Configuration();
while (1) {
Motor_Drive(500, 1); // 向一个方向驱动电机,速度为500
delay_ms(1000);
Motor_Drive(0, 1); // 停止电机
delay_ms(1000);
Motor_Drive(500, 0); // 向另一个方向驱动电机,速度为500
delay_ms(1000);
Motor_Drive(0, 1); // 停止电机
delay_ms(1000);
}
}
这个例子中,我们使用了一个定时器(TIM1)来产生PWM信号控制电机的速度。首先,我们通过GPIO初始化函数将相关引脚配置为正确的模式和功能。然后,我们使用TIM初始化函数配置定时器的时钟预分频、计数模式、周期等参数。接下来,我们通过TIM_OC初始化函数配置定时器的输出模式、极性等参数,并启动定时器。在主循环中,我们调用Motor_Drive函数来驱动电机,在每次调用函数前后加上delay_ms函数来控制电机转动的时间和停止的时间。
注意:这只是一个简单的示例代码,具体的电机驱动控制方法可能有所不同,具体取决于所使用的电机类型和驱动器。在实际的应用中,您需要根据您的具体需求和硬件配置进行适当的修改。