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?
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() 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.