MKRzero: Ultrasonic sensor HC-SR05 erratic reading when playing I2S Audio

Dear all NittyGritty is an open-source project of mine based on a MKRzero. The intention is to build a device (I already designed the PCB board) to play sound. It is to be used by sound-artists, interactive installations and exhibitions. I would like to publish everything as a DYI kit offering the diagram, board, box and code. It has an AdaFruit I2S Speaker and Headphone for output and a HC-SR05 sensor to trigger a sound file at a certain distance. All goes well, but when the "waveFile" is playing from the µSD card using the ArduinoSound.h function, the bounce time reading is wrong. It has to do with ISR iI suppose but how to avoid this. I tried using a correction factor but that's really crappy..

It depends, Post your schematic completer with all power and ground connections and also the software. If your software has delays it is probably best to get rid of them.

How do you actually measure the bounce time? You can’t use pulsein because that is blocking code which just counts how many times you go round the loop, and as you rightly say interrupts are steeling time from you.

You have two possible soloutions one is use a sensor that doesn’t need timing to get a distance. There is the IR distance sensor that gives an analogue output, or a time of flight sensor that just returns a digital number.

The other soloution is to use an interrupt to start and stop a timer that is being timed by the system clock. That of course will require some reading of how the timers work and to pick one that is not being used by anything else in your code.

Thanks Grumpy_Mike. I use the HC-SR05 because it’s cheap and goes 5meters. And I do use pulseIn (other option?). Timing independent sensors: any suggestions for under €5,- ? (I live in Belgium). I tried interrupts but then it’s either the sound or the sensor timing that stutters. So now I do a trick by interrupting the sound for a few µs only every 10 seconds and it works well for now… I’ll post the whole thing when this beta version runs later this week.
PS: can’t attach an image in Safari

What is the ultrasonic sensor doing in this setup?