0

I'm trying to use a stepper motor to stay stationary and rotate about 90 degrees, when the ultrasonic sensor detects something in front of it, and stay at that position until the ultrasonic sensor does not detect anything in front of it any more, to which the motor will rotate back to it's original position.

I'm using an Arduino Uno, a Longruner 5X Geared Stepper Motor 28byj 48 Uln2003 5v Stepper Motor with a Uln2003 Driver Board.

#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);


// defines pins numbers
const int trigPin = 7;
const int echoPin = 6;

// defines variables
long duration;
int distance;

void setup() {

   pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
   pinMode(echoPin, INPUT); // Sets the echoPin as an Input
   Serial.begin(9600); // Starts the serial communication
   myStepper.setSpeed(60);
    // initialize the serial port:  (again??)
   Serial.begin(9600);
}

void loop() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
   duration = pulseIn(echoPin, HIGH);

// Calculating the distance
   distance= duration*0.034/2;

// Prints the distance on the Serial Monitor
   Serial.print("Distance: ");
   Serial.println(distance);

   if (distance < 10) {
       myStepper.step(-stepsPerRevolution);
       delay(1000);
       if (distance > 10) {
           myStepper.step(stepsPerRevolution);
           delay(10000);
       }
   }
}

Here's my code. I can't really figure out how to stop/pause the stepper motor once it rotates. Any ideas? (I'm a beginner, so apologies for any beginner mistakes).

  • it is your job to tell us what you see happening when you run the program ... please edit your post above ... do not use comments – jsotola Jul 23 at 3:06
  • 1
    the stepper motor control and the ultrasonic sensor reading are two completely separate functions .... develop the stepper motor code separately from the sensor ... use a pushbutton to initiate the motor motion ... when the motor behaves the way you want it to behave, then add the sensor code – jsotola Jul 23 at 3:31
  • I do not think it is a major issue, but why are you calling Serial.begin() twice? – GMc Jul 23 at 6:52
  • Oops my mistake didn't catch that – Skrish Jul 24 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.