传送门:STM32控制ULN2003驱动步进电机28BYJ-48最基础版
使用串口调试步进电机28BYJ-48获得需要转速
当使用STM32控制ULN2003驱动步进电机28BYJ-48时,步进电机转速变化缓慢,想要得到合适的控制速度,需要不断的调试,不断的更改代码,编辑、编译、下载到STM32中,不断的重复下载造成开发速度慢同时对单片机也是一种损耗,废话不多说直接上代码。
- 定义struct.h进行宏定义,如下:
#define STRUCT(type) typedef struct _tag_##type type;\
struct _tag_##type
电机部分代码改进
- 在step_motor.h中定义类型,使用对象可以使数据组织起来使用更加方面,如下:
/* 类型定义 ------------------------------------------ */
STRUCT(StepMotor_t)
{
/*
*state: bit0 0 表示电机处于非运行态; 1 表示运行态
* bit1 0 表示电机正转 1 反转
*/
uint8_t state;
/* 每步时间片 */
uint16_t step_slice;
/* 总步数 */
u32 step_num;
void (*run)(StepMotor_t *motor);
};
- 在step_motor.c中定义电机运行函数,如下:
/**
* @name: Step_Motor_Run
* @description: step motor run.
* @param {StepMotor_t} *motor
* @return {*}
*/
void Step_Motor_Run(StepMotor_t *motor)
{
/* 判断正反转 */
if(!(motor->state & 0x02))
{
printf("motor ready run cw... , period is %d .\r\n", motor->step_slice);
Step_Motor_CW(motor);
}
else
{
printf("motor ready run ccw... , period is %d .\r\n", motor->step_slice);
Step_Motor_CCW(motor);
}
motor->state &= ~0x01;
}
- 同时进行运行正反转的函数定义:
/**
* @name: Step_Motor_CW
* @description: 电机正转函数
* @param {uint32_t} nms
* @return {*}
*/
static void Step_Motor_CW(StepMotor_t *motor)
{
volatile uint8_t i;
uint32_t j, pieces; /* pieces 表示8个位一组的脉冲一共多少组 */
uint8_t temp = 0;
pieces = motor->step_num / 8;
for(j = 0; j < pieces; j++)
for(i = 0; i < 8; i++)
{
temp = steps[i];
LA = (uint8_t)((temp&PLA) >> 0);
LB = (uint8_t)((temp