Control stepper motor using Ultrasonic sensor

Hi..i'm new to Arduino.

I need a help is Programming Arduino for my project. I need to control 2 Unipolar Stepper motors(28BYJ-48) using ultrasonic sensor HC-SR04.

Two stepper motors should run continuously and when the ultrasonic sensor gives a reading of 10Cm from the obstruction, both stepper motors should stop for the moment. Then one stepper motor-1 should rotate for a certain number of steps (lets say 100). After a delay of..say 5 secs, both stepper motors should resume rotation until the next obstruction of 10cm distance is observed. For the next obstruction, both motors should stop and Stepper Motor-2 should rotate for certain number of steps. After that a delay of 5sec and both motors should resume rotation again.

Its basically a obstacle avoiding robot which runs in a straight line and when the distance from the wall is 10cm, it turns around by 180 degree and moves in the opposite direction.

Any help in coding will be appreciated.

Stepper motor: 28BYJ-48 with ULN2003 controller
Arduino: MEGA

Thanx in advance.

Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.,148850.0.html.

Can you please tell us your electronics, programming, Arduino, hardware experience?

Basically you will be best to develop your code in stages.

  • Get code for the HC-SR04 working and reading distance, try NewPing library to make things easier.
  • Get code to get ONE stepper operating For/Back/Stop.
  • Adapt stepper code to do For/Back/Stop with two stepper motors.
  • Then when each stage is working, combine the two codes.

What are you going to use as a power supply, the steppers will need a separate supply to the Mega, or get their power from the same source as the Mega BUT not through the Mega board.

The IDE has some stepper libraries that will help and the Arduino site and tohers if you google will have some tutorials.

Tom.... :slight_smile:

Any help in coding will be appreciated.

We will be happy to help but you must do most of the work.

Post the program you have tried and tell us what part of it you need help with.


as i mentioned earlier i’m new to this platform. After combining two different codes for HC-SR04 & Stepper, I could get a partial result of my requirement. I have only connected one Stepper motor at the moment (Providing external power supply). I can run the Stepper and when the distance is <10cm, stepper is stopped as expected.
However one issue i’m facing at the moment is that there is a delay of almost 5 secs between 2 distance measurement readings on SERIAL MONITOR for distances more than 10cm.
As soon as it comes to less than 10cm reading, the stepper is getting stopped as expected, and the subsequent distance measurements are pretty fast (in intervals of millisecs).
Slow readings occur only when the distance is more than 10 cm. Here’s the code:
*#include <NewPing.h>

//Include the Arduino Stepper Library
#include <Stepper.h>

// Define Constants
// Number of steps per internal motor revolution
const float STEPS_PER_REV = 32;
//  Amount of Gear Reduction
const float GEAR_RED = 64;
// Number of steps per geared output rotation
// Define Variables
// Number of Steps Required
int StepsRequired;
// Create Instance of Stepper Class
// Specify Pins used for motor coils
// The pins used are 8,9,10,11
// Connected to ULN2003 Motor Driver In1, In2, In3, In4
// Pins entered in sequence 1-3-2-4 for proper step sequencing
Stepper steppermotor(STEPS_PER_REV, 8, 10, 9, 11);

// defines pins numbers for ultrasonic sensor
const int trigPin = 6;
const int echoPin = 7;
// defines variables for ultrasonic sensor
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

void loop()
// Clears the trigPin
digitalWrite(trigPin, LOW);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
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: ");

// Roatate Stepper if distance is more than 10cm
{// Rotate CW 1/2 turn slowly
 StepsRequired  =  2048;

Could someone help me with this…why the readings are as slow as 5 Sec when the sensor is clear of obstructions?
Thanx in advance

To make it easy for people to help you please modify your post and use the code button </> so your code looks like this and is easy to copy to a text editor. See How to use the Forum

Also please use the AutoFormat tool to indent your code for easier reading.


Why aren’t you using the NewPing library, you include it, but don’t use it.
Look in Examples in the IDE.

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.

void loop() {
  delay(50);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS =; // Send ping, get ping time in microseconds (uS).
  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)

Tom… :slight_smile:


i tried the example in newPing library; However the result is same. Surprisingly when I reduced the StepsRequired = 10 for Stepper, the intervals between the Ultrasonic readings more than 10cm became faster. :confused:

More frequent readings are being shown now for distances more than 10cm. I'm just wondering...what stepper motor steps has to do with the interval of Sonar readings.

Earlier when the StepsRequired was 500 'Tx' LED on Arduino board used to flash only once in ~5 was the interval b/w readings for distances more than 10 cm!

Once i reduced the stepsRequired to 10, 'Tx' LED on Arduino board is flashing faster and...more frequent readings are shown!?

Once i reduced the stepsRequired to 10, ‘Tx’ LED on Arduino board is flashing faster and…more frequent readings are shown!?

The way your program is written the Arduino can do nothing else until all the steps are complete. Hence it is more responsive with fewer steps.