Use HC-SR04 Ultrasonic Sensor to move a motor

It is so close to working.

I adjusted the code a little

#define trigPin 4

#define echoPin 5

#include <Stepper.h>

const int stepsPerRevolution = 400; //number of steps per 
                                    //revolution for your motor
 
 // initialize the stepper library on the motor shield
 Stepper myStepper(stepsPerRevolution, 12,13);     
 
 // give the motor control pins names:
 const int pwmA = 3;
 const int pwmB = 11;
 const int brakeA = 9;
 const int brakeB = 8;
 const int dirA = 12;
 const int dirB = 13;
 const int STOP = 0;
 
 int x = 0;

void setup() {

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

pinMode(pwmA, OUTPUT);
 pinMode(pwmB, OUTPUT);
 pinMode(brakeA, OUTPUT);
 pinMode(brakeB, OUTPUT);
 digitalWrite(pwmA, HIGH);
 digitalWrite(pwmB, HIGH);
 digitalWrite(brakeA, LOW);
 digitalWrite(brakeB, LOW);
 
  // initialize the serial port:
 Serial.begin(9600);
 // set the motor speed (for multiple steps only):
 myStepper.setSpeed(75);

}

void loop() {


  accel();

}

unsigned long dist()
{
  digitalWrite(trigPin, LOW); 

  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10); 

  digitalWrite(trigPin, LOW);

  return (pulseIn(echoPin, HIGH) / 2) / 29.1;

}

void accel(){
  
  unsigned long distance = dist ();
  
  delay(500); //Like I think you wanted me to.

  unsigned long dist2 = dist () - distance; //Still have to subtract the old distance for the rest to work.
  
  Serial.print (F("distance = "));
  Serial.println (distance);
  Serial.print (F("dist2 = "));
  Serial.println (dist2);

if (distance < 20){
  if (dist2 < 0){
    myStepper.setSpeed(75);
    myStepper.step(-4);
  }
    
  else if (dist2 == 0){
    myStepper.setSpeed(STOP);
  }
  
  else {
    myStepper.setSpeed(75);
    myStepper.step(4);
  }
}

else {
  if (dist2 < 0){
    myStepper.setSpeed(75);
    myStepper.step(4);
    }
    
  else if (dist2 == 0){
    myStepper.setSpeed(STOP);
    }  
 
  else {
    myStepper.setSpeed(75);
    myStepper.step(-4); 
  }
}
}

However it is now showing results like this once in a while...

distance = 5
dist2 = 0
distance = 5
dist2 = 4294967292
distance = 5
dist2 = 0
distance = 5
dist2 = 4294967292
distance = 5
dist2 = 4294967291

Now the motor only move when the object moves, so one goal accomplished :slight_smile: However it still only moves in one direction, and not one if the object is getting closer and the other if the object is moving away.