#define STEP_PIN 3
#define DIR_PIN 2
#define TRIG_PIN 7
#define ECHO_PIN 6
const int stepsPerRevolution = 200;
const int distanceThreshold = 20; // Adjust as needed (in cm)
void setup() {
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(9600); // For debugging
}
void loop() {
long duration, distance;
distance = calculateDistance();
Serial.print("Distance: ");
Serial.println(distance);
if (distance <= distanceThreshold) {
// Object detected: Rotate clockwise
digitalWrite(DIR_PIN, HIGH);
rotateStepper();
} else {
// No object detected: Stop motor
// (You don't need to explicitly turn it off)
}
delay(500); // Adjust the sensor reading interval
}
long calculateDistance() {
long duration; // Declare the variable here
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void rotateStepper() {
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(500);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(500);
}
}