Skip to content

Ultrasonic and Time-of-Flight Obstacle Avoidance Simulator

Run MicroSim in Fullscreen

Specification

The full specification below is extracted from Chapter 7: Building and Programming a No-Display STEM Robot.

Type: microsim
**sim-id:** obstacle-avoidance-simulator<br/>
**Library:** p5.js<br/>
**Template:** https://github.com/dmccreary/learning-micropython/tree/main/docs/sims/collision-avoidance-flowchart<br/>
**Status:** Specified

Learning objective: Students will *apply* (Bloom L3: Apply) a calibrated safe-distance threshold to trigger a simulated robot's obstacle avoidance and safety stop before it reaches a wall.

Canvas: 700x460px, responsive -- recompute arena and robot icon scale from `windowWidth` in `windowResized()`.

Layout: a side-view arena showing a robot icon on the left and a wall on the right, with a numeric "Distance to wall" readout above the arena updating live as the robot moves. A shaded "safe zone" band is drawn on the floor at the current threshold distance from the wall.

Controls: a `createSlider()` labeled "Safe Distance Threshold (cm)" (range 5-50, default 15); a `createButton()` labeled "Drive Forward" that starts the robot moving toward the wall at a constant simulated speed; a `createButton()` labeled "Reset" that returns the robot to its starting position; a `createCheckbox()` labeled "Simulate Sensor Noise" that, when checked, adds small random jitter to the displayed distance reading (reusing the noise-filtering idea from the previous chapter) without changing the robot's true position.

Interaction: as the robot drives forward, its distance readout counts down; the moment it crosses the threshold line, the robot icon visibly stops and a text banner reads "Obstacle detected -- safety stop." If "Simulate Sensor Noise" is checked and the threshold is set very close to the wall, occasional noisy readings can cause a visibly late stop, letting students discover experientially why a threshold needs a safety margin. Clicking the wall opens an infobox explaining time-of-flight versus ultrasonic sensing, matching the chapter's stated preference for time-of-flight sensors.

Implementation: p5.js, robot position advanced each frame by a fixed step while a `driving` boolean is true, with the true distance computed geometrically each frame and an optional noise term added before display. Threshold comparison drives both the stop logic and the safe-zone band's rendering, recomputed from the slider value every frame so the two always stay visually consistent.