Moving stepper motor with SR04 sensor

Hi, ive been googling this and trying to put together bits of code from various instructables but just cant get it working.

Its a really simple task; move a stepper motor 1 revolution when distance sensor registers distance <200.

Im using a L293 motor shield

This is what I have so far (im a beginner at this :))

#include <AFMotor.h>
#define TRIG_PIN A4 // Pin A4 on the Motor Drive Shield soldered to the ultrasonic sensor
#define ECHO_PIN A5 // Pin A5 on the Motor Drive Shield soldered to the ultrasonic sensor

What would the code be for this? Greatly appreciate the help

I am not familiar with the Adafruit motorshield or the Adafruit libraries but I am pretty sure they have example programs.

Can you get your motor moving in a program that does nothing else?

And in a completely separate program can you get readings from the sensor and display the numbers on the Serial Monitor?

Only try to join those concepts together when you can do each of them separately.

...R Stepper Motor Basics Simple Stepper Code

Cheers Robin, yes i was able to load the separate codes and get the sensor and motor working individually.

Ive managed to hack something together and it seems to work so i thought i’d share this very basic code for others to work from.

L293D Motor Shield (Adafruit Motor Shield V1)


#include <AFMotor.h>
#define trigPin A0
#define echoPin A1
AF_Stepper Stepper2(200, 2);   // A 200-step-per-revolution motor on channels 3 & 4

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  if (distance >= 600 || distance <= 0){
    Serial.println("Out of range");
    Stepper2.release(); // stop rotation and turn off holding torque.
  else if (distance < 40) {
    Stepper2.step(100, FORWARD, SINGLE); 
    Serial.println(" cm");
  else {
    Serial.println(" cm");