Hey, I am trying to use an ultrasonic sensor to control a stepper motor. I can get the sensor to turn the motor, but I need to stop the motor in place while the sensor is detecting something in a given range, and then rotate back to it's original spot
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??)
}
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);
}
}
}