STM32單片機驅動步進電機(一)
驅動電機運動
軟件:Keil5
設備:步進電機(17HS4401)、驅動器、單片機(STM32F103)
spa
接線方式:code
- 電機與驅動器:黑A+,綠A-,紅B+,藍B-
- 驅動器與單片機:MF-PC8,DR-PC9,PU-PB5,COM-3.3V
main.c:(註解部分爲這次用不上的程序)ip
#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:it
#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:io
#ifndef __TIMER_H #define __TIMER_H #include "sys.h" void TIM3_PWM_Init(u16 arr,u16 psc);
foot_definition.c:(名字隨意取得,用以存放調用串口的程序)class
#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脈衝發送的頻率,以達到控制電機轉速的目的。map