Arduino INTERRUPT to use on a sensor. HELP

Hi guys, my project involves using an HC-SR04 ultrasonic sensor to get the distance. The robot should stop when it hits a certain distance.

My question is: how can you apply interrupt so that the output coming out of the ultrasonic sensor can trigger the program to stop?

my current code is:

void loop()
if (distance is greater that 20cm)
{run the motor}
else
{stop motor}

the problem with this is it wastes so much processing power because it will continually check distance every loop cycle. and if my distance gets to the threshold while inside the if statement, it has to finish the loop first before stopping

I was thinking something like:

attachInterrupt (0, blink, LOW) //triggers when signal is low
void loop()
{run the motor}
void blink()
{stop motor}

So it will interrupt once we get a LOW output from ultrasonic sensor. But the problem is that the echo pin of ultrasonic sensor is not a square wave, so there's no LOW cycle.

So yes, I'm stuck atm.. Any thoughts would be appreciated. Do you have any suggestions on how to fix this, or any alternative techniques to make this work?

the problem with this is it wastes so much processing power because it will continually check distance every loop cycle.

No, that's not the problem (if it is, you're triggering the sensor far too often)
Try triggering and reading the sensor at no more than about 20Hz.

the problem with this is it wastes so much processing power because it will continually check distance every loop cycle.

What are you planning to do with the processing power that you save ?

if my distance gets to the threshold while inside the if statement, it has to finish the loop first before stopping

What else are you doing in loop() ? Nothing involving delay()s I hope.

yeah maybe processing power is not much of an issue. But the question remains: can you interrupt on something that is not a square wave?

UKHeliBob:
What are you planning to do with the processing power that you save ?
What else are you doing in loop() ? Nothing involving delay()s I hope.

Im also putting in a ton of code for my ESP8266 web interface, , i was a bit worried it might consume processing power. but will build it first i dont think it would be a problem

But the question remains: can you interrupt on something that is not a square wave?

What is it that is not a square or rectangular wave?
The HC-SR04 is a digital device.

the problem with this is it wastes so much processing power because it will continually check distance every loop cycle. and if my distance gets to the threshold while inside the if statement, it has to finish the loop first before stopping

Another vote here for not using delay.

Yes, the distance may get to the threshold while inside the if statement. However, does your if statement really take longer than the time to test and calculate distance?

I think the NewPing library also works with HC-SR04