i am developping an ultrasonic device to determine the 2d position - coordinates - of a robot moving inside a rectangle. basically, the robot sends a 40 khz pulse (when ePin is HIGH) which is received by 2 transducers (read as value_1 and value_2) placed at two corners of the rectangle. from the two times-of-flight ta and tb x and y can be calculated.

``````value_1 = analogRead(analogInput_1);
digitalWrite(ePin, HIGH);
t = millis();
while((value_1 < 300) && (value_2 < 300)){
tet = millis() - t;
}
if(value_1 > value_2){
ta = tet;
}
else{
tb = tet;
}
while((value_1 < 300) || (value_2 < 300))
{
tou = millis() - t;
}
if(ta == tet){
tb = tou;
}
else if(tb == tet){
ta = tou;
}
``````

typically, for my setup these times-of-flight vary from 0 to 10 milliseconds. this means using the function millis() i do not have much precision.
is there a possibility to measure microseconds instead?

The Arduino sets timer0 to increment every 64 cycles. When it overflows after 256 cycles it increments a variable that controls the millis() function. To get better resolution, you could peek at the counter by looking at TCNT0. You must be careful though, there are race conditions to confuse you. For instance... between the time you call millis() and check TCNT0 you don't know if millis() changed. It might be safest to do something like...

``````m1 = millis;
t0 = TCNT0;
m2 = millis;
if ( m1 == m2) {
// I know what I'm doing.
} else {
// I don't know. A low t0 might mean it is from after the millichange
// and a high might mean before, but we can't be really certain.
}
``````

And this isn't a documented API, so you never know when a release will change the resolution of timer0 and really mess you up very badly.

Sound only moves 1-2mm in air at this timer resolution, so it should be good. You just have to deal with the hassle of the race condition and the checking your code after Arduino releases. Welcome to life "outside the lines".