接线图:
代码配置:
根据驱动舵机的代码来写,与舵机不同的是,这次的引脚接到了PA2上,所以需要改一下引脚以及改为OC3通道。
另外还需在配置两个GPIO引脚,来控制电机的旋转方向,这里连接到了PA4与PA5引脚
整体代码:
void Motor_Init(void)
{//-----------------定义结构体变量----------------------GPIO_InitTypeDef GPIO_InitStructure; //定义GPIO结构体变量TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;//定义TimeBase结构体变量TIM_OCInitTypeDef TIM_OCInitStructure; //定义OC结构体变量//-----------------定义结构体变量----------------------//配置时钟RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//打开GPIO时钟RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);//打开TIM2时钟//-----------------配置GPIO----------------------------GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;//选择复用推挽模式GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //配置引脚GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速率GPIO_Init(GPIOA, &GPIO_InitStructure); //GPIO初始化//-----------------配置GPIO----------------------------//-----------------配置GPIO----------------------------GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;//选择推挽输出GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5;//配置引脚GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速率GPIO_Init(GPIOA, &GPIO_InitStructure); //GPIO初始化//-----------------配置GPIO----------------------------//-------------------配置时基单元----------------------TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;//时钟分频TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //计数器模式,这里选择向上计数TIM_TimeBaseInitStructure.TIM_Period = 100 - 1;//周期 就是自动重装器ARR的值TIM_TimeBaseInitStructure.TIM_Prescaler = 72 - 1;//预分频器 PSC的值TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; //重复计数器的值TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure); //TimeBase初始化//-------------------配置时基单元----------------------//------------------配置输出比较单元-------------------TIM_OCStructInit(&TIM_OCInitStructure); //给结构体赋初值TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//配置输出比较模式TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//设置输出比较极性TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //设置输出使能TIM_OCInitStructure.TIM_Pulse = 0;//CCR的值TIM_OC3Init(TIM2, &TIM_OCInitStructure);//------------------配置输出比较单元-------------------TIM_Cmd(TIM2,ENABLE);//开启定时器}
功能代码:
这里实现电机的正转与反转
void Motor_SetSpeed(int8_t Speed)
{if(Speed >= 0){GPIO_SetBits(GPIOA,GPIO_Pin_4);GPIO_ResetBits(GPIOA,GPIO_Pin_5);TIM_SetCompare3(TIM2,Speed);}else{GPIO_ResetBits(GPIOA,GPIO_Pin_4);GPIO_SetBits(GPIOA,GPIO_Pin_5);TIM_SetCompare3(TIM2,-Speed);}}
主函数:
#include "Motor.h"
int main(void)
{LED_Init();OLED_Init();KEY_Init();Motor_Init();int16_t Speed = 0;OLED_ShowString(1, 1, "Speed:");while(1){if(KEY_Scanf(GPIOB,GPIO_Pin_1) == 1){Speed += 20;if(Speed > 100){Speed = -100;}}Motor_SetSpeed(Speed);OLED_ShowSignedNum(1, 7, Speed, 3);}}