How to trigger an interrupt when a variable has a certain value?

I'm bulding a car robot that uses an ultrasonic sensor (the HC-SR04) to detect objects around it.
The sensor measures the distance between the robot and an object and that value is stored in a variable. I want to create an interrupt that is triggered when the distance is equal or lower than a certain value, so I can use the void loop() function for other things meanwhile the sensor is looking for objects.

But all examples I have seen of attachInterrupt() are triggered with a low or high pulse on an input pin, either with rising, falling, change or low. How can it be triggered with a varaible value? Is that possible?

It's possible (requires a pin change interrupt) but not really desireable.
I suspect your software design needs a rethink

There is no reason your loop() function can't do multiple things. Consider the following tutorials:


Arduino Multiple Things

Several Things at a Time

How is that stored? Just compare the value you store to your threshold and call your function when this happens…

Am I missing something here?

To avoid waiting for pulseIn() to read the length of the ECHO pulse, connect the ECHO pin to an interrupt pin and use a CHANGE interrupt. When the ECHO pin is HIGH, the ISR notes the time (startTime = micros():wink: and then the pin is LOW, calculate the time difference (duration = micros() - startTime;). The loop() can then read the new duration and calculate distance whenever it needs to. You only need to pulse the TRIGGER pin about ever 50 milliseconds.

Better still, if you've only got one sensor, use the input capture facility.