最近在研究电机,于是想写一篇文章来记录我的学习历程。下面是用PWM来驱动电机,涉及的电机驱动是L298N。
大概的思路:初始化连接电机的IO口,配置定时器的PWM模式,配置电机IO口的电平。
代码如下:
#include "moto.h"
void MOTO_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void MOTO_Mode(char state)
{
if(state == GO)
{
GPIO_SetBits(GPIOB,GPIO_Pin_13);
GPIO_ResetBits(GPIOB,GPIO_Pin_12);
}
if(state == BACK)
{
GPIO_SetBits(GPIOB,GPIO_Pin_12);
GPIO_ResetBits(GPIOB,GPIO_Pin_13);
}
if(state == STOP)
{
GPIO_ResetBits(GPIOB,GPIO_Pin_12);
GPIO_ResetBits(GPIOB,GPIO_Pin_13);
}
}
void Car_Go(void)
{
MOTO_Mode(GO);
}
#include "timer.h"
void MOTO_PWM_Init(u16 arr, u16 psc)
{
TIM_OCInitTypeDef TIM_OCInitSructure;
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
TIM_TimeBaseStructure.TIM_Period = arr;
TIM_TimeBaseStructure.TIM_Prescaler = psc;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);
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(GPIOB, &GPIO_InitStructure);
TIM_OCInitSructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitSructure.TIM_OutputState= TIM_OutputState_Enable;
TIM_OCInitSructure.TIM_Pulse = 2300;
TIM_OCInitSructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC3Init(TIM3, &TIM_OCInitSructure);
TIM_OC3PolarityConfig(TIM3, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM3, ENABLE);
TIM_Cmd(TIM3, ENABLE);
}
main函数
#include "stm32f10x.h"
#include "moto.h"
#include "timer.h"
#include "sys.h"
#include "delay.h"
int main()
{
MOTO_GPIO_Init();
MOTO_PWM_Init(3599,0);
delay_init();
while(1)
{
Car_Go();
}
}
若觉得这篇文章写得不错,可以点个赞嗷~
下篇文章准备写用PID控制电机!想要的话可以关注哦!
|