The HC-SR04 sonar modules are available for a mere pittance and, with some coaxing, can do a pretty decent job of helping your robot measure the distance to the nearest wall. But when sellers on eBay are shipping these things in ten-packs, why would you stop at mounting just one or two on your ‘bot? Octosonar is a hardware and Arduino software library that’ll get you up and running with up to eight sonar sensors in short order.
Octosonar uses an I2C multiplexer to send the “start” trigger pulses, and an eight-way OR gate to return the “echo” signal back to the host microcontroller. The software library then sends the I2C command to select and trigger a sonar module, and a couple of interrupt routines watch the “echo” line to figure out the time of flight, and thus the distance.
Having two sonars on each side of a rectangular robot allows it move parallel to a wall in a straightforward fashion: steer toward or away from the wall until they match. Watch the video below for a demo of this very simple setup. (But also note where the robot’s 45-degree blind spot is: bump-bump-bump!)
With three address bits available on the I2C multiplexer, you could add another eight sonars to a project while only demanding one more interrupt pin from your host microcontroller. Heck, at the prices these things go for, why not go for the full 64?!
The comments for this project suggest a couple of alternative ways to go: a different pair of standard multiplexers instead of I2C, a CPLD to handle the logic, or whatever. But if you just want a simple setup, Octosonar has got you covered. If you’d like to dive deep into the HC-SR04 modules, check out this complete reverse engineering and brain transplant or this similar dissection of the modules with great references.