#include "stm32f10x.h" #include "stm32f10x_gpio.h" #include "stm32f10x_rcc.h" #include "stm32f10x_tim.h"

#define STEPPER_PIN_1 GPIO_Pin_0 #define STEPPER_PIN_2 GPIO_Pin_1 #define STEPPER_PIN_3 GPIO_Pin_2 #define STEPPER_PIN_4 GPIO_Pin_3

#define NUM_STEPS 200

void delay_ms(uint32_t ms) { for (volatile uint32_t i = 0; i < ms * 1000; i++); }

void stepper_init(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = STEPPER_PIN_1 | STEPPER_PIN_2 | STEPPER_PIN_3 | STEPPER_PIN_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);

}

void stepper_step(int dir) { static int step = 0; if (dir > 0) { step++; if (step > 3) { step = 0; } } else { step--; if (step < 0) { step = 3; } }

if (step == 0) {
    GPIO_SetBits(GPIOA, STEPPER_PIN_1);
    GPIO_ResetBits(GPIOA, STEPPER_PIN_2 | STEPPER_PIN_3 | STEPPER_PIN_4);
} else if (step == 1) {
    GPIO_SetBits(GPIOA, STEPPER_PIN_1 | STEPPER_PIN_2);
    GPIO_ResetBits(GPIOA, STEPPER_PIN_3 | STEPPER_PIN_4);
} else if (step == 2) {
    GPIO_SetBits(GPIOA, STEPPER_PIN_2 | STEPPER_PIN_3);
    GPIO_ResetBits(GPIOA, STEPPER_PIN_1 | STEPPER_PIN_4);
} else if (step == 3) {
    GPIO_SetBits(GPIOA, STEPPER_PIN_3 | STEPPER_PIN_4);
    GPIO_ResetBits(GPIOA, STEPPER_PIN_1 | STEPPER_PIN_2);
}

delay_ms(2);

}

int main(void) { stepper_init();

while (1) {
    for (int i = 0; i < NUM_STEPS; i++) {
        stepper_step(1);
    }
    delay_ms(1000);
    for (int i = 0; i < NUM_STEPS; i++) {
        stepper_step(-1);
    }
    delay_ms(1000);
}
写的一段c语言代码要求可以用stm32f103控制步进电机运动

原文地址: http://www.cveoy.top/t/topic/hhlH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录