Arduino+A4988控制步进电机

*脚6(-en) 低电平为启动电机(enable),貌似也可以不接,试过一样能运行.但如果要控制电机的启动关闭还是要用上

*脚4(-dir) 用高低电平控制方向.

*脚5(-step) 用高低电平驱动电机转动.注意中间间隔等待的微秒值,如果太快会导致电机有声响不转动.

const int stepPin = 12; //D6
const int dirPin = 14; //D5
const int enable = 16; //D0 
const int key1 = 5; //D1  前进0.5
const int key2 = 4; //D2  后退0.5
const int key3 = 0; //D3  后退至0
int ButtonState = HIGH;
void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT); 
  pinMode(dirPin,OUTPUT);
  pinMode(enable,OUTPUT); 
  pinMode(key1,INPUT_PULLUP); 
  pinMode(key2,INPUT_PULLUP);
  pinMode(key3,INPUT_PULLUP); 
  Serial.begin(9600);
  Serial.println("Sensor Test");
  Serial.println("");
}

void step(boolean dir, int steps) 
{
digitalWrite(enable, LOW);//enable
digitalWrite(dirPin, dir); //dir=1
delay(50);
for (int i = 0; i < steps; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(800);
digitalWrite(stepPin, LOW);
delayMicroseconds(800);
}
digitalWrite(enable, HIGH);//disable
}

void addone() //前进0.5
{
int reading = digitalRead(key1); 
  if (reading != ButtonState) {
   delayMicroseconds(500);
   reading = digitalRead(key1); 
    if (reading == LOW) {
        step(true, 200); delay(500); 
        Serial.println("----------------前进--------------------");
      }
  }
}

void minone() //后退0.5
{
 int reading = digitalRead(key2); 
  if (reading != ButtonState) {
   delayMicroseconds(500);
   reading = digitalRead(key2); 
    if (reading == LOW) {
        step(false, 200); delay(500); 
        Serial.println("----------------后退--------------------");
      }
  } 
}

void zreoone() //后退到0
{
 int reading = digitalRead(key3); 
  if (reading != ButtonState) {
   delayMicroseconds(500);
   reading = digitalRead(key3); 
    if (reading == LOW) {
         for (int i = 0; i < 2; i++) {
                                           step(false, 500); delay(500); 
                                           delayMicroseconds(800);
                                           Serial.println("----------------KEY3--------------------");
                                      }
                          } 
 
  }

void estkey()  //按键判断
{
Serial.println("----------------OK--------------------");
}

void loop() 
{
addone();
minone();
zreoone();
}

参考文章 Arduino+A4988+步进电机    按键消抖

猜你喜欢

转载自blog.csdn.net/yyandad/article/details/100904278