51单片机俩个按钮控制四相八拍固定电机转动代码
时间: 2023-07-04 12:30:07 浏览: 56
下面是一个简单的51单片机俩个按钮控制四相八拍固定电机转动的代码:
```
#include <reg51.h>
//定义端口
sbit MotorPin1 = P1^0;
sbit MotorPin2 = P1^1;
sbit Button1 = P2^0;
sbit Button2 = P2^1;
//定义电机状态
enum MotorState {STOP, FORWARD, BACKWARD};
MotorState motorState = STOP;
//定义8种电机状态
unsigned char motorStateTable[8] = {0x01, 0x03, 0x02, 0x06, 0x04, 0x0C, 0x08, 0x09};
unsigned char motorStateIndex = 0;
void delay(unsigned int n)
{
while(n--);
}
void MotorRun()
{
MotorPin1 = motorStateTable[motorStateIndex] & 0x01;
MotorPin2 = (motorStateTable[motorStateIndex] >> 1) & 0x01;
}
void main()
{
//初始化电机引脚
MotorPin1 = 0;
MotorPin2 = 0;
while(1)
{
//判断按钮1是否按下
if(Button1 == 0)
{
delay(1000); //延时去抖动
if(Button1 == 0)
{
motorState = motorState == FORWARD ? STOP : FORWARD;
}
while(Button1 == 0); //等待按钮弹起
}
//判断按钮2是否按下
if(Button2 == 0)
{
delay(1000); //延时去抖动
if(Button2 == 0)
{
motorState = motorState == BACKWARD ? STOP : BACKWARD;
}
while(Button2 == 0); //等待按钮弹起
}
//根据电机状态更新电机状态表的索引
switch(motorState)
{
case STOP:
motorStateIndex = 0;
break;
case FORWARD:
motorStateIndex++;
if(motorStateIndex >= 8)
{
motorStateIndex = 0;
}
break;
case BACKWARD:
if(motorStateIndex == 0)
{
motorStateIndex = 7;
}
else
{
motorStateIndex--;
}
break;
}
MotorRun(); //更新电机状态
delay(1000); //延时
}
}
```
在这个代码中,我们使用了P1的0和1号引脚来控制电机的正反转,使用了P2的0和1号引脚来控制电机的方向。当按下按钮1时,电机正反转状态切换为正转或停止;当按下按钮2时,电机正反转状态切换为反转或停止。
代码中使用了一个电机状态表,其中包含了8种不同的电机状态,分别对应电机的8种不同的运行状态。当需要更新电机状态时,我们根据当前的电机状态来更新电机状态表的索引,然后根据索引值来更新电机的状态,从而实现电机的正反转和转动方向的控制。
需要注意的是,这个代码只是一个简单的示例,具体的电机控制方式可能会有所不同,需要根据具体的电机驱动方式来进行调整。