pulseIn with ultrasonic sensor taking too long

I am experiencing an issue with the pulseIn function, which causes a significant delay of around 700 milliseconds in my code. Below is the function I am using to get the counter distance:

void get_Counter_Distance() { long start = millis();

digitalWrite(counter_trigpin, LOW);
delayMicroseconds(2);
long s1 = millis();
digitalWrite(counter_trigpin, HIGH);
delayMicroseconds(10);
long s2 = millis();
digitalWrite(counter_trigpin, LOW);
long s3 = millis();

// Measure the duration of the echo
long counter_duration = pulseIn(counter_echopin, HIGH, 100000);
long s4 = millis();

// Calculate the distance in cm
counter_distance = counter_duration * 0.034 / 2;
long end = millis();
if (s4 - s3 > 200) {
Print_Lcd_Message("warning delay", "get ctr dist", 0);
Serial.println(s4 - s3);
}
// Serial.print("get_Counter_Distance() took:");
// Serial.print(end - start); Serial.print(",");
// Serial.print(s1 - start); Serial.print(",");
// Serial.print(s2 - s1); Serial.print(",");
// Serial.print(s3 - s2); Serial.print(",4-3: ");
// Serial.print(s4 - s3); Serial.print(",");
// Serial.print(end - s4); Serial.print(",");
// Serial.println(counter_distance);
}

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

In my experience the easiest way to tidy up the code and add the code tags is as follows
Start by tidying up your code by using Tools/Auto Format in the IDE to make it easier to read. Then use Edit/Copy for Forum and paste what was copied in a new reply. Code tags will have been added to the code to make it easy to read in the forum thus making it easier to provide help.

I wonder why you are not checking for zero? Zero is returned if the time-out value is reached.

Which Arduino? Which ultrasonic sensor?

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