# Measuring distance by ultrasonic transducer (not using pulseIn() )

Hi everyone, I have a project which measures the distance of an object to the transducer based on the time of the returning echo.
My ultrasonic transducer is not suitable for using pulseIn() function. So I measure by keep reading the level of the signal at the echo pin using analaRead() and see if it exceeds a voltage threshold. The echo signal is a sine wave and last for about 1ms.
I write the code but it doesn’t work properly. The results of the time betwenn transmitting and receiving are not stable even if the object stays still.
I guess the problem is: the execution time of the reading loop is too long (about 150us per cycle). And because the echo signal is a sine wave so if the code reads the signal at the negative part of the echo, then it also doesn’t work.
The following is my code, can someone help me? Thanks a lot

#define iteration 25

int pingPin = 12; // LED connected to digital pin 9
int echoPin = A0;
double voltage;

boolean gotEcho = false;
double transmitTime = 0;
double duration;
int i;

void setup() {

Serial.begin(9600);
pinMode(pingPin, OUTPUT);
}

void loop() {
gotEcho = false;
i = 0;

for (int i=0; i<20; i++) // exite the transducer by 10 pulses with frequency 40kHZ, 5V
{
digitalWrite(pingPin, LOW);
delayMicroseconds(7);
digitalWrite(pingPin, HIGH);
delayMicroseconds(6);
}
digitalWrite(pingPin, LOW);

transmitTime = micros();
while((i < iteration)&&(gotEcho == false)) // Keep reading the signal level at the echo pin
{

if((voltage > 9)) // Voltage Threshold
{
if((gotEcho == false) )
{
gotEcho = true;
}
}
else
{
i++;
}
}

if(gotEcho == true)
{
Serial.println(duration);
delay(1000);
}
else
{
delay(10);
}
}

In the 100us that it takes to do an analogRead, your sound has traveled about 34mm (17mm round-trip).
Add to that the extra time it takes to do all that fiddly time-consuming floating point arithmetic, your measurements are going to have a lot of jitter.
Could you use the analogue comparator instead?

Thanks very much @AWOL