When the ultrasonic sensor determines that there is an object within a certain range, I want to make the step motor move once, but the step motor does not move. The step motor lights up, but I don't know what the problem is. Except for the conditional syntax and ultrasonic sensor, the step motor works well when you run the step motor.
The code is as follows:
#include <AccelStepper.h>
int a;
int trigPin4 = A1;
int echoPin4 = A2;
long duration4, distance4;
// Define step constants
#define FULLSTEP 4
#define HALFSTEP 8
#define motorPin1 8
#define motorPin2 9
#define motorPin3 10
#define motorPin4 11
#define motorPin5 4
#define motorPin6 5
#define motorPin7 6
#define motorPin8 7
AccelStepper stepper1(FULLSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
AccelStepper stepper2(FULLSTEP, motorPin5, motorPin7, motorPin6, motorPin8);
void setup()
{
pinMode(trigPin4, OUTPUT);
pinMode(echoPin4, INPUT);
Serial.begin(9600);
// 1 revolution Motor 1 CW
stepper1.setMaxSpeed(1000.0);
stepper1.setAcceleration(50.0);
stepper1.setSpeed(100);
stepper1.moveTo(2048);
// 1 revolution Motor 2 CCW
stepper2.setMaxSpeed(1000.0);
stepper2.setAcceleration(50.0);
stepper2.setSpeed(100);
stepper2.moveTo(-2048);
}
void loop()
{
digitalWrite(trigPin4, LOW);
delayMicroseconds(2);
digitalWrite(trigPin4, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin4, LOW);
duration4 = pulseIn(echoPin4, HIGH);
distance4 = duration4 * 0.034 / 2;
if (distance4 >= 500 || distance4 <= 0) {
Serial.println("Out of range");
}
else {
Serial.print("Sensor4 : ");
Serial.print(distance4);
Serial.println("cm");
a = 1;
}
if (a == 1) {
stepper1.run();
stepper2.run();
}
delay(2000);
}
question from:
https://stackoverflow.com/questions/65868323/stepper-motor-does-not-work-when-used-with-ultrasonic-sensor-and-step-motor-in-a 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…