|
按你的要求,那就不用锁住按键。照下面这样可能就行了:
int motorPin1 = 13;
int motorPin2 = 5;
int motorPin3 = 4;
int motorPin4 = 2;
const int KEY1 = 12; // 正传按钮
const int KEY2 = 14; // 反转按钮
int motorSpeed = 1200; //设置步进速度
int KEY1_NUM = 0;
int KEY2_NUM = 0;
int lookup[8] = {B01000, B01100, B00100, B00110, B00010, B00011, B00001, B01001};
void setup() {
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);
pinMode(KEY1, INPUT);
pinMode(KEY2, INPUT);
Serial.begin(115200);
}
void loop()
{
ScanKey();
if (KEY1_NUM == 1)
{
KEY1_NUM = 0;
clockwise();//正传
anticlockwise();//反转
}
if (KEY2_NUM == 1)
{
KEY2_NUM = 0;
anticlockwise();//反转
clockwise();//正传
}
}
void ScanKey() //按键
{
if (digitalRead(KEY1) == HIGH)
{
delay(30);
if (digitalRead(KEY1) == HIGH)
{
KEY1_NUM = 1;
while (digitalRead(KEY1) == HIGH);
}
}
if (digitalRead(KEY2) == LOW) //按键2检测
{
delay(30);
if (digitalRead(KEY2) == LOW)
{
KEY2_NUM = 1;
while (digitalRead(KEY2) == LOW);
}
while (digitalRead(KEY2) == LOW);
}
}
void clockwise() //顺时针
{ for (int j = 0; j < 5; j++)
{
for (int i = 7; i >= 0; i--)
{
setOutput(i);
delayMicroseconds(motorSpeed);
}
}
}
void anticlockwise() //逆时针
{
{ for (int i = 0; i < 8; i++)
{
setOutput(i);
delayMicroseconds(motorSpeed);
}
}
}
void setOutput(int out)
{
digitalWrite(motorPin1, bitRead(lookup[out], 0));
digitalWrite(motorPin2, bitRead(lookup[out], 1));
digitalWrite(motorPin3, bitRead(lookup[out], 2));
digitalWrite(motorPin4, bitRead(lookup[out], 3));
} |
|