STM32F103RCT6 步进电机 PWM 控制 C 代码
#ifndef __MOTOR_H
#define __MOTOR_H
#include "stm32f10x.h"
#define MOTOR_STEP_PIN GPIO_Pin_0
#define MOTOR_DIR_PIN GPIO_Pin_1
#define MOTOR_PORT GPIOA
void Motor_Init(void);
void Motor_SetDirection(uint8_t dir);
void Motor_Step(void);
#endif
#include "motor.h"
void Motor_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = MOTOR_STEP_PIN | MOTOR_DIR_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(MOTOR_PORT, &GPIO_InitStructure);
}
void Motor_SetDirection(uint8_t dir)
{
if (dir == 0)
{
GPIO_ResetBits(MOTOR_PORT, MOTOR_DIR_PIN);
}
else
{
GPIO_SetBits(MOTOR_PORT, MOTOR_DIR_PIN);
}
}
void Motor_Step(void)
{
GPIO_SetBits(MOTOR_PORT, MOTOR_STEP_PIN);
GPIO_ResetBits(MOTOR_PORT, MOTOR_STEP_PIN);
}
#ifndef __PWM_H
#define __PWM_H
#include "stm32f10x.h"
#define PWM_TIM TIM3
#define PWM_TIM_CLK RCC_APB1Periph_TIM3
#define PWM_TIM_IRQn TIM3_IRQn
#define PWM_TIM_IRQHandler TIM3_IRQHandler
#define PWM_GPIO_PORT GPIOA
#define PWM_GPIO_PIN GPIO_Pin_6
#define PWM_GPIO_CLK RCC_APB2Periph_GPIOA
void PWM_Init(uint16_t period, uint16_t duty_cycle);
void PWM_SetDutyCycle(uint16_t duty_cycle);
#endif
#include "pwm.h"
void PWM_Init(uint16_t period, uint16_t duty_cycle)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB1PeriphClockCmd(PWM_TIM_CLK, ENABLE);
RCC_APB2PeriphClockCmd(PWM_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = PWM_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(PWM_GPIO_PORT, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = period - 1;
TIM_TimeBaseStructure.TIM_Prescaler = SystemCoreClock / 1000000 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(PWM_TIM, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = duty_cycle - 1;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(PWM_TIM, &TIM_OCInitStructure);
TIM_Cmd(PWM_TIM, ENABLE);
}
void PWM_SetDutyCycle(uint16_t duty_cycle)
{
TIM_SetCompare1(PWM_TIM, duty_cycle - 1);
}
#include "stm32f10x.h"
#include "motor.h"
#include "pwm.h"
int main(void)
{
Motor_Init();
PWM_Init(1000, 500);
while (1)
{
Motor_SetDirection(0);
for (int i = 0; i < 200; i++)
{
Motor_Step();
PWM_SetDutyCycle(i);
for (int j = 0; j < 10000; j++);
}
Motor_SetDirection(1);
for (int i = 199; i >= 0; i--)
{
Motor_Step();
PWM_SetDutyCycle(i);
for (int j = 0; j < 10000; j++);
}
}
}
原文地址: https://www.cveoy.top/t/topic/jrJX 著作权归作者所有。请勿转载和采集!