Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

Stepper motor does not work when used with ultrasonic sensor and step motor in Arduino

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

first, do not use "delay" function. Second, put a= 0 to the first if statement because in your code, once the distance satisfies the the else condition the value of a will remain 1 forever


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...