I have a project that needs to have an Ultrasonic detector attached to the to the top of a stepper motor. I however I want the radar to mover either between 15 - 165 degrees or 0 and 180. But I can only get the motor to rotate a full 360. I can see when the motor is delaying when it should change directions but it stays in one direction.
If the problem is not code then I believe it might be the wires. But when I follow the datasheet and pin input the stepper moves too slow and still does't change direction.
I have attached the code here and a hand drawn schematic of what I think might be a wiring issue.
#include <Stepper.h>.
// Defines Ti and Echo pins of the Ultrasonic Sensor
const int trigPin = 10;
const int echoPin = 11;
const int steps = 800;
// Variables for the duration and the distance
long duration;
int distance;
Stepper myStepper(steps , 2,4,3,5);
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600);
// set the speed at 60 rpm:
myStepper.setSpeed(20);
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
// rotates the stepper motor from 15 to 165 degrees
for(int i=0;i<=165;i++){
myStepper.step(i);
delay(30);
distance = calculateDistance();// Calls a function for calculating the distance measured by the Ultrasonic sensor for each degree
Serial.print(i);
Serial.print(",");
Serial.print(distance);
Serial.print(".");
}
// Repeats the previous lines from 165 to 15 degrees
for(int i=165;i>=15;i--){
myStepper.step(i);
delay(30);
distance = calculateDistance();
Serial.print(i);
Serial.print(",");
Serial.print(distance);
Serial.print(".");
}
}
// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
distance= duration*0.034/2;
return distance;
}
