Ultrasonic and Proximity Sensors for Collision Avoidance
The cheapest reliable obstacle sensor on a drone is also the most physics-driven. An ultrasonic module costs a few dollars, measures distance to any solid surface regardless of color, and answers the single question avoidance logic cares about most: how much room is in front of me. Its limitations â a widening cone, temperature sensitivity, and slow updates â define exactly where it can be trusted and where a rangefinder or camera must take over.
This lesson derives the time-of-flight calculation with temperature compensation, compares ultrasonic against infrared time-of-flight sensors, lays out multi-sensor coverage around an airframe, and builds an avoidance controller plus a small occupancy mapper from raw echoes.
How ultrasonic ranging works
An ultrasonic transducer pair behaves like bat echolocation. The transmitter emits a short burst at 40 kHz â well above human hearing â the pulse travels out, reflects off a surface, and returns to the receiver. Distance follows from halving the round-trip time multiplied by the speed of sound:
distance = (speed of sound à echo time) / 2
At 20 °C the speed of sound is about 343 m/s, so an echo returning after 10 ms corresponds to roughly 1.7 meters. Most common modules report accuracy around ¹1 cm with a beam angle between 15 and 30 degrees, a minimum range near 2 cm, and a maximum between 4 and 10 meters depending on target reflectivity.
Two behaviors matter for flight. First, the beam is a cone, not a line: at 3 meters a 20-degree half-angle covers a spot over two meters wide, so a thin branch can fall between echoes or a nearby wall can dominate the reading. Second, the sound speed changes with temperature â roughly 0.6 m/s per degree Celsius â which is a one percent error per few degrees, small for indoor hover but worth correcting outdoors.
Time-of-flight with temperature compensation
The compensated model is simple enough to run on a microcontroller. The class below converts echo time in microseconds to meters and exposes the timeout needed to bound wait time when nothing reflects.
class UltrasonicSensor:
"""Time-of-flight ranging with temperature compensation."""
def __init__(self, temperature_c=20.0):
self.temperature = temperature_c
self.min_range_m = 0.02
self.max_range_m = 4.0
def speed_of_sound(self):
"""Empirical approximation: 331.3 + 0.606 * T, in meters per second."""
return 331.3 + 0.606 * self.temperature
def distance_from_echo(self, echo_time_us):
"""Round-trip echo time in microseconds to one-way distance."""
speed = self.speed_of_sound()
seconds = echo_time_us / 1_000_000
return (speed * seconds) / 2
def timeout_us(self, max_distance=None):
"""Echo timeout that bounds the wait at maximum range."""
max_distance = max_distance or self.max_range_m
return (2 * max_distance / self.speed_of_sound()) * 1_000_000
def classify(self, distance):
if distance is None or distance >= 2.0:
return "CLEAR"
if distance >= 1.0:
return "CAUTION"
if distance >= 0.3:
return "SLOW"
return "STOP"
sensor = UltrasonicSensor(temperature_c=25.0)
for echo_us in (580, 1160, 2900, 5800):
dist = sensor.distance_from_echo(echo_us)
print(f"echo {echo_us} us -> {dist:.2f} m ({sensor.classify(dist)})")
A practical driver always sets the timeout: without it a missed echo blocks the loop for the maximum sound travel time, and a ring of five sensors polled in sequence turns into sluggish update rates.
Ultrasonic versus infrared time-of-flight
Infrared ToF sensors modulate a light pulse and measure its phase or travel time instead of sound. They are faster, narrower, and immune to temperature â but sunlight washes out their receivers, and dark or specular surfaces return little energy. Ultrasonic sees matte, transparent-to-light, and colored surfaces equally well but struggles with sound-absorbing fabric and struggles in wind that deflects the pulse.
| Property | Ultrasonic | Infrared ToF |
|---|---|---|
| Wave | 40 kHz sound | Modulated IR light |
| Range | 0.02â10 m | 0.02â4 m typical |
| Accuracy | About Âą1 cm | Âą1â2 cm |
| Update rate | 20â50 Hz | 50â100 Hz |
| Surface dependence | Absorbs soft fabrics | Fails on dark or glossy targets |
| Sunlight | Unaffected | Direct sunlight degrades range |
| Beam width | 15â30 degrees | 10â25 degrees |
| Temperature effect | Speed of sound drifts | Negligible |
Complementary mounting exploits both: ultrasonic downward for terrain and landing surfaces, infrared forward where sunlight exposure is manageable and fast updates matter. If either sensor is the sole input for a safety stop, you have built a single point of failure.
Detection zones around the airframe
Five sensors â front, rear, left, right, bottom â give rough spherical coverage. The bottom sensor handles altitude hold over ground and landing detection; the four horizontal sensors feed velocity limiting. Convert raw distance into behavior with explicit thresholds so the control layer receives decisions, not numbers.
class ObstacleAvoidance:
"""Map sensor readings to action classes and a repulsive velocity."""
def __init__(self):
self.stop_m = 0.3
self.slow_m = 1.0
self.cautious_m = 2.0
def analyze(self, readings):
closest = min(readings, key=readings.get)
distance = readings[closest]
if distance < self.stop_m:
action = "EMERGENCY_STOP"
elif distance < self.slow_m:
action = "REDUCE_SPEED"
elif distance < self.cautious_m:
action = "CAUTIOUS"
else:
action = "CLEAR"
return action, closest, distance
def repulsive_vector(self, readings):
"""Sum inverse-distance repulsion from each close obstacle."""
vector = [0.0, 0.0]
axes = {"front": (0, -1), "rear": (0, 1),
"left": (-1, 0), "right": (1, 0)}
for direction, distance in readings.items():
if direction in axes and distance < self.cautious_m:
force = 1.0 / max(distance, 0.1)
dx, dy = axes[direction]
vector[0] += dx * force
vector[1] += dy * force
magnitude = (vector[0] ** 2 + vector[1] ** 2) ** 0.5
if magnitude > 0:
scale = min(magnitude, 1.0) / magnitude
vector = [vector[0] * scale, vector[1] * scale]
return vector
avoidance = ObstacleAvoidance()
readings = {"front": 0.8, "left": 2.5, "right": 1.5, "rear": 3.0, "bottom": 1.2}
action, closest, distance = avoidance.analyze(readings)
vector = avoidance.repulsive_vector(readings)
print(f"action={action} closest={closest} at {distance:.2f} m")
print(f"repulsive velocity = ({vector[0]:+.2f}, {vector[1]:+.2f})")
Note that the stop threshold is deliberately small â 0.3 m â while caution begins at 2 m. At typical indoor speeds of 1â2 m/s the aircraft covers its stopping distance inside the slow zone; set thresholds tighter than your dynamics allow and the vehicle will oscillate between states instead of braking smoothly.
Building a small occupancy map
Single echoes are noisy. Fusing them over time into an occupancy grid filters dropouts and turns the sensor set into a map you can plan against. Rays clear cells along their path and darken only the terminal cell, exactly the logic lidar stacks use, at ultrasonic resolution.
import math
class UltrasonicMapper:
"""Accumulate ultrasonic rays into a 2D occupancy grid."""
def __init__(self, cells=100, resolution_m=0.1):
self.cells = cells
self.resolution = resolution_m
self.grid = [[0.5 for _ in range(cells)] for _ in range(cells)]
def _world_to_cell(self, x, y):
gx = int(x / self.resolution) + self.cells // 2
gy = int(y / self.resolution) + self.cells // 2
return gx, gy
def ray_cast(self, start, angle, distance, confidence=1.0):
end_x = start[0] + distance * math.cos(angle)
end_y = start[1] + distance * math.sin(angle)
gx0, gy0 = self._world_to_cell(*start)
gx1, gy1 = self._world_to_cell(end_x, end_y)
steps = max(abs(gx1 - gx0), abs(gy1 - gy0), 1)
for i in range(steps + 1):
t = i / steps
gx = int(gx0 + (gx1 - gx0) * t)
gy = int(gy0 + (gy1 - gy0) * t)
if 0 <= gx < self.cells and 0 <= gy < self.cells:
if i < steps:
self.grid[gy][gx] = max(0.1, self.grid[gy][gx] - 0.05)
else:
self.grid[gy][gx] = min(0.9, self.grid[gy][gx] + 0.3 * confidence)
def update(self, position, heading, readings):
offsets = {"front": 0.0, "left": 1.5708,
"right": -1.5708, "rear": 3.1416}
for name, distance in readings.items():
if name in offsets and distance and distance > 0:
confidence = max(0.3, 1.0 - distance / 5.0)
self.ray_cast(position, heading + offsets[name], distance, confidence)
def obstacles(self, threshold=0.7):
found = []
for y in range(self.cells):
for x in range(self.cells):
if self.grid[y][x] > threshold:
found.append((x, y))
return found
mapper = UltrasonicMapper()
readings = {"front": 1.5, "left": 3.0, "right": 2.0, "rear": 4.0}
mapper.update((5.0, 5.0), 0.0, readings)
print(f"mapped {len(mapper.obstacles())} occupied cells")
Confidence decays with distance because the cone widens and echo reliability falls â a five-meter return deserves less cell weight than a half-meter one. With the grid in place, planning code can treat unknown space conservatively and treat high-value cells as hard obstacles.
Filtering, hysteresis, and fusion
Raw ultrasonic streams are spiky: a single missed echo reads as maximum range while a specular reflection off a glossy panel reads far closer than reality. The cheapest effective filter is a rolling median of the last five echoes per sensor â it discards outliers without the lag a heavy moving average would add, and it runs comfortably on any flight controller. Pair the median with a rate limiter so one glitchy ping cannot flip the action state twice within a control cycle.
Hysteresis prevents state oscillation near a threshold. Instead of switching between slow and cautious at exactly one meter, enter the slower state below one meter and only return to cautious above 1.15 meters. The small gap absorbs sensor noise, so the aircraft settles into a steady speed instead of surging and braking every time the reading brushes the boundary. The same principle applies to the emergency stop: latch it briefly once triggered, because a stop that immediately cancels on the next clean ping will stutter the aircraft into the obstacle it was trying to avoid.
Fusion layers sensors by reliability rather than averaging them blindly. Downward ranging from ultrasonic pairs with barometer and rangefinder for altitude; forward infrared takes precedence in bright light while ultrasonic covers the same sector when the sun goes down or the surface is matte. When two sensors disagree, trust the one whose operating conditions currently match its specification, and log the disagreement â persistent conflicts usually mean one sensor has been fouled, loose, or shadowed by a newly mounted accessory.
Common Mistakes
Treading a single ultrasonic reading as truth
Fix: Filter with a median of the last five echoes; one specular miss must not trigger an emergency stop.
Mounting sensors where propeller wash or frame arms sit inside the cone
Fix: Clear the beam of airframe structure and propeller tips, or the drone will see itself forever.
Ignoring temperature when flying outdoors between seasons
Fix: Compensate speed of sound from a temperature sensor if you need centimeter accuracy across conditions.
Using one sensor class for every direction
Fix: Pair ultrasonic for downward and indoor ranging with infrared or lidar forward where sunlight and update rate matter.
Best Practices
- Poll sensors in a round-robin that keeps each update rate above 20 Hz; slower loops blur obstacles during motion.
- Set echo timeouts explicitly so a dead transducer degrades to a stale reading instead of a hung loop.
- Log raw echoes alongside the action decisions to tune thresholds from real incidents.
- Validate safety thresholds in a controlled walk test before enabling avoidance in flight.
- Treat bottom-range readings separately for landing detection â ground proximity needs its own hysteresis.
Key Takeaways
- Ultrasonic ranging is time-of-flight on sound: halve the round-trip echo time times the speed of sound, compensated about 0.6 m/s per degree Celsius.
- Ultrasonic and infrared ToF sensors are complementary â sound sees any surface but updates slower; light is fast but fails in sun and on dark targets.
- Beam cones and multi-sensor layouts create coverage and blind spots that must be mapped before trusting avoidance.
- Convert distances into explicit action zones â stop, slow, caution, clear â sized to the aircraft's braking dynamics.
- Accumulate filtered echoes into an occupancy grid with confidence weighting so planning operates on fused evidence rather than raw pings.