Suggestionn on Interrupts, sensors and real time application

I developing a mobile robot with my Arduino Mega and a pc which i use to read data from Arduino via USB.

I'm using four sonar sensors (SRF08 on I2C bus), a 2-axis gyroscope and two encoders.

I'd like to use interrupts in order to make my arduino application as much real-time as possible.
With interrupt I can detect if one of the four sonars is detecting a collision and i can communicate this event in time to my pc with serial communication.
The problem is that i'm already using interrupts for my two encoder in order to calculate rpms and distance.

Do you think it is still possible to use interrupts also for my sonars?
What are your suggestions about the interrupts using?

Can i avoid to use them since i'm using USB communication?

The Mega has more than two external interrupts.

However, I don't see how you can use interrupts with the sonar devices. You have to ask them for the distance they are seeing. They are not proactive devices that can generate an interrupt when the distance goes below some value.

Can't I write some function which can generate an interrupt when a distance comes below some value?

:frowning:

You could set up a regular tick interrupt, for example using the MsTimer2 library. You have to send a command to the SFR to range, wait for the ranging to take place, then read the results from the SFR08. So I suggest you read the results from all 4 sensors at the beginning of the tick ISR, check for imminent collisions and schedule any remedial action, then send range commands to all 4 sensors and exit the tick ISR. The interval between ticks needs to be long enough for the range command sent at the end of one execution of the ISR to complete before the next tick interrupt - see SFR08 datasheet for details of the timing.

Can't I write some function which can generate an interrupt when a distance comes below some value?

I suppose you could, but in order for that function to generate an interrupt, you have to call that function quite often, and it have to measure the distance. If the function knows that the distance is less than some value, why does it need to generate an interrupt whose handler sets a flag that loop then detects on the next pass? Just set the flag directly.