Hi, I have a Nema-17 connected to a TMC2208, connected to a CNC shield connected to an Arduino Uno. I also have a HC-SR04 sensor.
The intention of my code is for the Nema-17 to run until the HC-SR04 detects something within 5cm. Once something is detected the Nema-17 will return to it's original position then the sequence will play out again but with the Nema-17 rotating in the anticlockwise direction.
When I run this code everything I just mentioned works however, when the Nema-17 runs clockwise and anticlockwise the Nema-17 runs extremely slow, but when the Nema-17 returns to its origin it runs at the speed I have set.
I'm assuming there is something in the code that is blocking the Nema-17 running at the speed I have set such as the "while" statement but I'm not sure how to fix it.
Additionally, I'm using the CNC shield because I am planning on running multiple motors off the same arduino, there are also photos below the code showing the wiring.
Any help would be greatly appreciated, thank you.
#include <AccelStepper.h>
#define EN 8
#define X_DIR 5
#define X_STP 2
#define TRIG_PIN A0
#define ECHO_PIN A1
AccelStepper stepperX(AccelStepper::DRIVER, X_STP, X_DIR);
long measureDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 30000);
if (duration == 0) {
return -1;
}
long distance = (duration / 2) / 29.1;
return distance;
}
void setup() {
stepperX.setMaxSpeed(1000);
stepperX.setAcceleration(500);
Serial.begin(9600);
pinMode(EN, OUTPUT);
digitalWrite(EN, LOW);
stepperX.setCurrentPosition(0);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.println("Home position set to current location: 0");
}
void loop() {
long distance;
Serial.println("Rotating clockwise until object is detected");
stepperX.setSpeed(1000);
while (true) {
distance = measureDistance();
if (distance != -1) {
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
} else {
Serial.println("No object detected");
}
if (distance > 0 && distance < 5) {
Serial.println("Object detected within 5 cm, stopping motor");
stepperX.stop();
break;
}
stepperX.runSpeed();
}
delay(1000);
Serial.println("Returning to home position");
stepperX.moveTo(0);
while (stepperX.distanceToGo() != 0) {
stepperX.run();
}
delay(1000);
Serial.println("Rotating counterclockwise until object is detected");
stepperX.setSpeed(-1000);
while (true) {
distance = measureDistance();
if (distance != -1) {
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
} else {
Serial.println("No object detected");
}
if (distance > 0 && distance < 5) {
Serial.println("Object detected within 5 cm, stopping motor");
stepperX.stop();
break;
}
stepperX.runSpeed();
}
delay(1000);
Serial.println("Returning to home position");
stepperX.moveTo(0);
while (stepperX.distanceToGo() != 0) {
stepperX.run();
}
delay(1000);
}

