Controlling a stepper motor with an ultrasonic sensor

HI, I am new to the forum, I hope I will find help.

I am doing a university project where the aim is to build an inner pipe climber robot.
I have attached a part of my code where I am stuck.
In this part I am using an Ultrasonic sensor and a stepper motor. The part 'void ultra' is the code to measure the distance with an ultrasonic sensor. However when I am measuring the distance as well as running the motor, the motor runs suddenly super slowly, however when I run the motors without the part of the code related to the ultrasonic sensor, it runs at normal speed.

I think that this might be due to the pulseIn function. PLEASE HELP me , I have no clue on how to solve this. This is the first time this ever happens to me.

Thank you !!

/////CODE/////

int Stoppage = 0;

// defines pins numbers

int trigPin = 2; // Trigger
int echoPin = 3; // Echo
long duration, cm;

void setup() {
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
digitalWrite(8, LOW);
digitalWrite(9, LOW);

pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop()
{
Ultra();
digitalWrite(9, HIGH);
delayMicroseconds(300);
digitalWrite(9, LOW);
delayMicroseconds(300);

}
void Ultra()
{
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(5);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) /29.1;
Serial.print(distance);
Serial.print("cm");
Serial.println();
}

test_case_normal_avec_int.ino (813 Bytes)

Why is "Ultra" void?
Why not return the range read?

However when I am measuring the distance as well as running the motor, the motor runs suddenly super slowly,

What if pulseIn times-out?

Why not use code tags?

what do you mean by "Why not return the range read?" ?

What is time out ? could you be clearer ?

Well, you never use the ultrasonic range, so why bother with the call to Ultra?

How far does sound in air travel in 300 microseconds?

What is time out ?

It's what happens when the receiver can't detect an echo.

could you be clearer ?

How long have you got? When is the assignment due?

i have until thursday, the aim is then to take the distance and reverse the stepper motor direction if the distance is under 10 cm and stop if it is around 50 cm

How do you get to 10cm if the motor is stopped at 50cm?

reverse the stepper motor direction if the distance is under 10 cm and stop if it is around 50 cm

AWOL:
How do you get to 10cm if the motor is stopped at 50cm?

I think OP means when the distance is under 10cm, reverse direction until the distance is around 50cm. Then stop.