yorkbarney 发表于 2025-4-24 12:30

控制28byj48步进电机



#include <reg52.h>
#include <intrins.h>

#define motorPort P1    // 步进电机的控制引脚连接到P1口
#define clockwise 0   // 顺时针方向
#define counterclockwise 1// 逆时针方向

// 函数声明
void delay(unsigned int time);
void motorRotate(unsigned char direction, unsigned int steps);

void main()
{
    while (1)
    {
      // 正转,执行一定的步数 (这里为512步,可根据需要修改)
      motorRotate(clockwise, 512);
      delay(1000);// 延时1秒

      // 反转,执行一定的步数
      motorRotate(counterclockwise, 256);
      delay(1000);// 延时1秒
    }
}

// 延时函数
void delay(unsigned int time)
{
    unsigned int i, j;
    for (i = time; i > 0; i--)
    {
      for (j = 110; j > 0; j--);// 指令周期延时
    }
}

// 控制步进电机旋转
void motorRotate(unsigned char direction, unsigned int steps)
{
    unsigned int i;
    unsigned char motorSequence = {0x01, 0x03, 0x02, 0x06, 0x04, 0x0C, 0x08, 0x09};// 步进电机的控制序列

    for (i = 0; i < steps; i++)
    {
      if (direction == clockwise)
      {
            motorPort = motorSequence;
      }
      else if (direction == counterclockwise)
      {
            motorPort = motorSequence;
      }

      delay(2);// 每步之间的延时,可根据需要调整
    }

    motorPort = 0x00;// 停止电机
}

Amazingxixixi 发表于 2025-4-24 13:47

学习一下
页: [1]
查看完整版本: 控制28byj48步进电机