I had a HC-SR04 ultrasonic distance sensor lying around. You can buy these for under £4 and they’re common in robot vehicle projects to stop them bumping into things. I managed to hook one up to a micro:bit and not just get distance readings but use them to alter the pitch of sound too.
You’ll need an external power supply for the sonar device – they need 5 volts and the 3 volts off a micro:bit board isn’t enough to make it work. I used 3 AAA batteries as a power source, but I imagine you could also use an old USB lead with the end chopped off instead. You also need a common ground, so make sure that the GND pin on the sensor is connected to the GND pin on your micro:bit as well as the negative terminal on its power supply. This ensures that the electrons that carry data between the sensor and the micro:bit have a complete circuit.
The code itself is very simple – just add the sonar block extensions and it’s as simple as this:
I added some buttons to turn it on and off as it can get a bit annoying after a while!
What else could you do with this? A commenter on my YouTube channel suggests attaching another one to control volume as well as pitch – micro:bit sound doesn’t have a volume function but it’s an intriguing idea, perhaps a second sensor could control something else like lights or octave shifts?