Step Motor-Ultrasonic Sensor Speed

Hi

I am using Nema-17 Step Motor and HC-SR04 ultrasonic module for my project. Between my codes below, I only add the sensor but my motor loses its speed and it gets slower. What is my mistake?

Thank you so much.


#include <AccelStepper.h>

#define motorInterfaceType 1

#define stepPin 2
#define dirPin 5


AccelStepper stepper_x(motorInterfaceType, stepPin, dirPin);

void setup(){
   stepper_x.setMaxSpeed(1000); 
     stepper_x.setSpeed(250);
   
}

void loop() {
 
       stepper_x.runSpeed();
   
}

My code with sensor:


#include <AccelStepper.h>

#define motorInterfaceType 1

#define stepPin 2
#define dirPin 5
const int trigPin = 8; 
const int echoPin = 10; 

AccelStepper stepper_x(motorInterfaceType, stepPin, dirPin);

void setup() {
  Serial.begin(9600);
   stepper_x.setMaxSpeed(1000); 
   pinMode(trigPin, OUTPUT); 
   pinMode(echoPin, INPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2; 

  Serial.print("Dist: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  if (distance < 10) {
    stepper_x.setSpeed(200); 
  } else {
    stepper_x.setSpeed(250); 
    stepper_x.runSpeed();
  }
  
}

Well, there are two problems:
1 pulseIn is a blocking function and stops the sketch until the pulse is measured.
2 You have stepper_x.runSpeed inside an if statement. It should be at the end of loop()

You can use interrupts to measure pulse width.
This tutorial explains how

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.