[LKS32 硬件] 控制28BYJ-48步进电机按指定的角度进行正转和反转

[复制链接]
 楼主| yorkbarney 发表于 2025-4-24 22:30 | 显示全部楼层 |阅读模式



  1. // 定义28BYJ-48步进电机的相序
  2. unsigned char stepSequence[8] = {0x01, 0x03, 0x02, 0x06, 0x04, 0x0C, 0x08, 0x09};

  3. // 定义步进电机当前位置和角度
  4. unsigned char currentPosition = 0;
  5. unsigned int currentAngle = 0;

  6. // 延时函数
  7. void delay(unsigned int time) {
  8.     unsigned int i, j;
  9.     for (i = 0; i < time; i++) {
  10.         for (j = 0; j < 120; j++);
  11.     }
  12. }

  13. // 步进电机正转函数
  14. void stepForward(unsigned int angle) {
  15.     unsigned int steps = angle / 5;  // 每步转动角度为5度
  16.     unsigned int i;
  17.    
  18.     for (i = 0; i < steps; i++) {
  19.         currentPosition++;
  20.         if (currentPosition >= 8) {
  21.             currentPosition = 0;
  22.         }
  23.         
  24.         P1 = stepSequence[currentPosition];
  25.         delay(10);  // 控制步进电机转速,可调整延时时间
  26.     }
  27.    
  28.     currentAngle += angle;
  29. }

  30. // 步进电机反转函数
  31. void stepBackward(unsigned int angle) {
  32.     unsigned int steps = angle / 5;  // 每步转动角度为5度
  33.     unsigned int i;
  34.    
  35.     for (i = 0; i < steps; i++) {
  36.         if (currentPosition == 0) {
  37.             currentPosition = 8;
  38.         }
  39.         
  40.         currentPosition--;
  41.         
  42.         P1 = stepSequence[currentPosition];
  43.         delay(10);  // 控制步进电机转速,可调整延时时间
  44.     }
  45.    
  46.     currentAngle -= angle;
  47. }

  48. // 主函数
  49. void main() {
  50.     while (1) {
  51.         // 正转180度
  52.         stepForward(180);
  53.         delay(1000);  // 停顿1秒钟
  54.         
  55.         // 反转90度
  56.         stepBackward(90);
  57.         delay(1000);  // 停顿1秒钟
  58.     }
  59. }


幸福小强 发表于 2025-5-25 20:26 | 显示全部楼层
好久没玩过步进电机了,准备弄一个玩玩,这个驱动用什么芯片
您需要登录后才可以回帖 登录 | 注册

本版积分规则

39

主题

1511

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部