简体   繁体   中英

Control Stepper Motor with A4988 Driver motor Using LDR Sensor

Hello i am now trying to control stepper motor using LDR sensor. im using NEMA 17 Stepper motor with A4988 motor driver. when i put code for LDR module, in serial monitor just show 1 data and not looping. when i using L298N, is not problem. i try to change from serial.print and delay but still not working. does anyone know the problem is it? this is the code:

 const int stepPin =  4;
 const int dirPin = 5;

int trig_pin = 2;
int echo_pin = 3;
long echotime;
float distance;


void setup() {
  Serial.begin(9600);
  pinMode(trig_pin, OUTPUT);
  pinMode(echo_pin, INPUT);
  digitalWrite(trig_pin, LOW);

  
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);

}

void loop() {
  //For Ultrasonic Sensor
  digitalWrite(trig_pin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig_pin, LOW);
  echotime = pulseIn(echo_pin, HIGH);
  distance= 0.0001*((float)echotime*340.0)/2.0;
  Serial.print(distance);
  Serial.println(" cm");
  delay(3600);

  //for LDR 
  unsigned int AnalogValue;
  AnalogValue = analogRead(A2);
  delayMicroseconds(10);
  Serial.println(AnalogValue);
  
  //for Stepper
  digitalWrite(dirPin, HIGH);
  for (int x = A2; x < 400; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  delay(1000);

  digitalWrite(dirPin, LOW);
  for (int x = A2; x > 400; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  delay(1000);

  digitalWrite(dirPin, HIGH);
  for (int x = A2; x = 400; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  delay(1000);
    
  }

for (int x = A2; x = 400; x++) is an infinite loop.

x = 400 evaluates to 400, which is a true value so the loop runs forever. I think you should revisit the basics of C++ control structures.

Also why do you start at A2 ? That's a pin number. Doesn't make sense to me. You probably wanted do use AnalogValue

for (int x = A2; x > 400; x++) is another non-sense loop. it will only run if A2 is > 400 and then it will run forever. But it is unlikely A2 will ever be > 400. So you could as well just remove that loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM