The main blocking part of your code is this bit:
while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
if((micros() - time) >= 100000) {
continue;
}
}
That is saying "While the echo pin is low, check the time. If too much time has passed then carry on with the loop".
So basically that will loop until the echo pin goes high, regardless of the time.
The continue command means to jump back to the beginning of the loop that it's in, be that a while, for, or do loop. In this case it jumps back to the beginning of the while loop it's in.
Instead you should consider using break, which means "Terminate this loop and carry on with what comes next".
Ultrasound sensing with pulseIn(), while simple to perform is rarely particularly accurate. Any interrupts that occur during the sensing will affect the outcome, and it's only as accurate as the micros() function allows it to be.
If you need a more precise and reliable measurement you should consider using one of the Input Capture modules in the ATMega. I don't know if there is a library to do it off hand, but programming it through the registers shouldn't be that difficult - just read the datasheet to find out how it all works.
Briefly the operation of IC is:
- Send trigger pulse
- Start IC timer counting
- Pulse arrives
- IC stops counting automatically and interrupt is triggered
- Read counter value and convert to microseconds.
- Set flag to indicate a result is available
The timing source is the main system clock and counting happens in the background completely parallel to the operation of the CPU, so nothing can interrupt it or delay it. Even if the execution of the IC interrupt routine is delayed by another interrupt running the counter value will have already stopped incrementing, so it will have been "captured" and give the correct result every time.