STM32单片机驱动步进电机(一)
驱动电机运动
软件:Keil5
设备:步进电机(17HS4401)、驱动器、单片机(STM32F103)
接线方式:
- 电机与驱动器:黑A+,绿A-,红B+,蓝B-
- 驱动器与单片机:MF-PC8,DR-PC9,PU-PB5,COM-3.3V
main.c:(注解部分为此次用不上的程序)
#include "led.h"
#include "delay.h"
#include "key.h"
#include "sys.h"
#include "usart.h"
#include "timer.h"
#include "foot_definition.h"
int main(void)
{
TIM3_PWM_Init(99,99);
PC89_Init();
//uart1_init(115200);//PA9 PA10
//uart2_init(115200);//PA2 PA3
//uart3_init(115200);//PB10 PB11
delay_init();
//KEY_Init();
LED_Init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
while (1)
{
GPIO_SetBits(GPIOC,GPIO_Pin_9);
GPIO_SetBits(GPIOC,GPIO_Pin_8);
TIM_Cmd(TIM3, ENABLE);
LED1=!LED1;
}
}
time.c:
#include "timer.h"
#include "led.h"
#include "usart.h"
void TIM3_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = arr;
TIM_TimeBaseStructure.TIM_Prescaler =psc;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_Pulse=arr;
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_Cmd(TIM3, DISABLE);
}
time.h:
#ifndef __TIMER_H
#define __TIMER_H
#include "sys.h"
void TIM3_PWM_Init(u16 arr,u16 psc);
foot_definition.c:(名字随意取得,用以存放调用串口的程序)
#include "foot_definition.h"
#include "stm32f10x_it.h"
#include "delay.h"
void PC89_Init(void) //
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8|GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
GPIO_ResetBits(GPIOC,GPIO_Pin_8); //MF
GPIO_ResetBits(GPIOC,GPIO_Pin_9); //DIR
}
foot_definition.h:
#ifndef _FOOT_DEFINITION_H
#define _FOOT_DEFINITION_H
void PC89_Init(void);
可以通过修改 TIM3_PWM_Init(99,99) 括号中的两个参数来改变PWM脉冲发送的频率,以达到控制电机转速的目的。