Robots can try and avoid obstacles through the use of “distance sensors” such as ultrasonic sensors or infrared sensors. These sensors work by emitting a signal and then waiting for an echo of that signal to return. The time it takes for the round trip indicates how far away an object is. In the case of ultrasonic sensors, the signal is a high pitched sound (well above levels that humans can hear) and in the case of infrared sensors it is a light wave with a high wavelength that is not visible. There are pros and cons to each approach, but here at Super Awesome Robots, we prefer ultrasonic sensors.
A popular ultrasonic sensor is the HC-SR04. These are very cheap sensors, usually costing less than $5 each and do a great job at measuring distance as long as you follow some good guidelines for using them correctly. For more information, see our Arduino with HC-SR04 tutorial!
A common approach to obstacle avoidance is to have three sensors on a robot, with one facing forward, and two facing slightly to the left or right. If an object is detected at front left, then the robot can start to turn right for example.
Sometimes obstacle avoidance can go wrong of course, so it’s always good if the robot can recognize when it has hit an object. A popular approach is to add physical sensors such as switches that are triggered on impact. The robot could be programmed to stop turning its motors in this case, to prevent them from overheating, or could be programmed to back up and turn and try again.