Ultrasonic Sensor - pulseIn

Hello,

I know the expamples using the ultrasonic sensors with the pulseIn function.
Why isn't it posslbe to get the duration with the arduino time functions and a while-structure?

long time1;
long time2;
int dauer;

time1=micros();

while(digitalRead(echo)==0){
Serial.println(digitalRead(echo));
}

time2=micros();
dauer=time2-time1;

You can. Only disadvantage with your approach is that it will hang forever if there is no echo.

FYI, your serial prints might interfere with your measurement.

You should be able to find the source code of pulseIn on your computer to see what it exactly does.

But it does not work- I get the same duration with every distance...

In most of the hardware cores, the pulseIn function has been written in assembly to be as efficient as possible so that it can accurately measure very short pulses. There is no reason you can't implement the same sort of code in your own sketch to get the same performance, but it's quite convenient to be able to share a common function from the core library between all your sketches, rather than repeating the same code in every sketch that needs the pulseIn() functionality. At least in the Arduino AVR Boards core, I know that they left the C code the assembly is based on as a comment to use as a reference:

jindriska:
But it does not work- I get the same duration with every distance...

That is not a problem of the pulseIn() function.
Maybe you miswired the sensor. Maybe the sensor is broken. Maybe the sensor really doesn't pick up a signal.

Hi,
Welcome to the forum.
Thanks for using tags.

Have you tried the NewPing library to do the distance calculations for you.

google
arduino newping library

It makes using the ultrasonic unit so mush easier.

Thanks… Tom… :slight_smile:

The Serial.println(digitalRead(echo)) statement will limit the resolution of your while loop.

digitalRead is 4 microseconds and there are two of these per loop.

More significantly Serial.println is at least 10_bitsPerChar / baudrate * numberOfCharacters with at least 3 characters per loop (0, carriage return, line feed). At 9600 baud this would be something over 3 milliseconds.

The speed of sound is about 340 meters/second so 3 milliseconds time LSB gives about 1 meter round trip distance resolution which is a pretty lousy implementation for a sensor with an effective range of a couple meters.

If you lose the print inside your while loop, the program should work well enough to demonstrate the concept.