#define trigPin 13
#define echoPin 10
#define stepPin 2
#define dirPin 5
#define enablePin 8
void setup() {
// Initialize the pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(enablePin, OUTPUT);
// Enable the stepper motor driver (enable pin is usually active LOW)
digitalWrite(enablePin, LOW); // Enable the driver
Serial.begin(9600); // Start the serial communication for debugging
}
void loop() {
// Send a pulse to the trigPin to start the measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the time for the pulse to return to echoPin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm (speed of sound is 343 m/s, so divide by 2 for round trip)
long distance = (duration / 2) * 0.0344;
// Print the distance for debugging
Serial.print("Distance: ");
Serial.println(distance);
// If an object is detected within 10 cm, rotate the stepper motor
if (distance < 10) {
// Set the direction (HIGH for clockwise, LOW for counterclockwise)
digitalWrite(dirPin, HIGH); // For example, HIGH for clockwise rotation
// Rotate the stepper motor by sending pulses to the stepPin
for (int i = 0; i < 200; i++) { // Adjust 200 for the number of steps to make a full rotation
digitalWrite(stepPin, HIGH);
delayMicroseconds(1000); // Adjust speed (this controls how fast the motor turns)
digitalWrite(stepPin, LOW);
delayMicroseconds(1000); // Adjust speed (this controls how fast the motor turns)
}
} else {
// Stop the motor (no pulses sent to stepPin means motor stops)
Serial.println("No object detected within 10 cm.");
}
delay(500); // Wait before measuring again
}