Engineering · Robot Autonomy · Perception

Where Am I? Mapping & Localization

Imagine waking up in a dark room you have never seen. Where are the walls? Where are you? Robots have to answer both questions at the same time. Help a robot draw a map with laser “flashlights,” then make your own map of the classroom with a tape measure.

A robot dropped into a new building knows nothing: not where the walls are, and not where it is. Every self-driving car, warehouse robot, and robot vacuum has to answer two questions at once — what does the world look like? and where am I in it? Build a map from laser scans, then recreate the experiment with an ELEGOO ultrasonic sensor or a tape measure. Watch position errors distort a map and use a cloud of guesses to find a lost robot.

Ages 6–18 · 3 levels1–2 class periodsSim + classroom buildsNo electronics required
← Back to Engineering
A robot in a room sweeping laser rays that turn grey unknown cells into white free cells and black wall cells grey = unknown · white = free · black = wall

Explorer · Story time

Where am I? What's around me?

I’m Bolt. When I roll into a new room, I can’t see like you. Instead, I shine invisible laser beams all around me, like lots of tiny flashlights. Each beam tells me how far away the wall is.

Every place a beam goes through must be empty floor. The place where it stops must be a wall. I color my map one square at a time: white for floor, black for wall, gray for “I don’t know yet.”

But here is the tricky part. My wheels slip a little, so I’m never totally sure where I am. If I get my place wrong, my map gets smeary!

  • Map · a picture of a place from above
  • Laser · a thin beam of light
  • Distance · how far away
  • Lost · not sure where you are

Try it as a class

  1. Blindfold map. With a partner keeping you safe, close your eyes and walk slowly with a hand out. Each time you touch something, your partner puts a sticky note on a big paper map. How much of the room can you map?
  2. Tape-measure robot. Stand in one spot. Measure the distance to the wall in front, behind, left, and right. Draw dots on graph paper. Move one big step and do it again. The dots start to show the room!
  3. Where’s the robot? One student secretly stands somewhere and only says their four distances to the walls. Can the class find the spot?

The big idea

Two questions that need each other

If a robot had a perfect map, it could figure out where it is by comparing what its sensors see against the map. That is localization. If it knew exactly where it was at every moment, it could build a map by recording what its sensors see from each spot. That is mapping. In an unknown place it has neither — so it must do both at once. Engineers call that SLAM: Simultaneous Localization And Mapping.

Sensing

A LiDAR spins a laser and times each bounce, giving a ring of distances. Cameras, sonar, and depth sensors do similar jobs.

Every reading is a little wrong. Noise is normal, not a bug.

Moving

Odometry counts wheel turns (encoders) and measures turning (a gyro) to estimate how far the robot moved.

Tiny errors add up. After a few laps, the robot's belief can be meters off.

Remembering

An occupancy grid splits the floor into cells. Each cell stores the probability it is blocked, starting at "no idea."

This grid is exactly what a planner like A* searches.

Classroom fieldwork

Build a map of your own

Start with a tabletop room made from upright cardboard walls. Mark a sensor station on graph paper, then measure distances in several directions. You can reproduce the key ideas without buying a LiDAR or building a driving robot.

Paper + tape measure

20–30 minutes · No electronics. Students act as sensor, mapper, and position tracker. Best first encounter with free, occupied, and unknown space.

ELEGOO sonar station

45–60 minutes after setup · UNO R3, HC-SR04, optional positional servo. Collect real echoes and plot them in the scan notebook below.

Robot-car extension

One extra class · Stop at marked stations and scan. Compare measured position with a motion estimate to reveal drift.

What we are modeling: these activities use known or manually measured sensor positions. They demonstrate mapping and localization separately; they do not run a complete SLAM algorithm. Ultrasound spreads into a cone, so its echoes are less precise in direction than the sim’s laser rays.

Paper + tape measure: become the robot

Gather: graph paper, ruler or tape measure, protractor, pencil, cardboard walls, and three colored pencils. Work in teams of three: sensor operator, mapper, and checker. Use a 10 cm grid for a tabletop room or a larger taped floor grid.

  1. Predict: put a paper robot at a marked station facing the top of the page. Predict which parts of the room one scan can reveal.
  2. Measure: at 30°, 60°, 90°, 120°, and 150°, measure from the robot’s center to the first wall. Here 90° is straight ahead, 0° is right, and 180° is left. Do not measure through an obstacle.
  3. Map: draw each measurement to scale. Mark the endpoint occupied, cells crossed before it free, and everything behind it unknown. Leave unmeasured gaps unknown, too.
  4. Test drift: move the robot 20 cm right. First plot the new scan as if it moved 25 cm; then plot it using the measured 20 cm. Which walls agree?
  5. Compare: overlay the map on the cardboard room. Label one area the sensor never saw. Explain why “unknown” does not mean “empty.”

DIY variations: rotate a ruler around a paper protractor for a tiny desk model, or use taut string and a tape measure for a floor map. Keep students’ eyes open; the mapper can face away from the room and receive only angle/distance reports.

ELEGOO UNO R3 + HC-SR04: map with sound

Gather: a 5 V UNO R3-compatible board (such as ELEGOO), USB cable, HC-SR04 ultrasonic module, breadboard, jumper wires, cardboard walls, and a protractor. Optional: an SG90-style positional servo and a regulated 5 V servo supply. Check your kit inventory; not every ELEGOO kit contains these parts.

Mount the sensor level with the walls. Tape its base down at a known station. Start with large, flat targets 20–100 cm away; keep fabric and narrow table legs out of the first test. Aim from the midpoint between the two transducers.

Stationary scanner wiring · UNO R3 only
Component leadConnect toReason
HC-SR04 VCC / GNDUNO 5 V / GNDSensor power and reference
HC-SR04 TRIG / ECHOD7 / D8Send a pulse / time the returning echo
Servo signal (often orange/yellow)D9Command the scan angle
Servo + (often red)External regulated 5 V +Supply rated for the servo’s current
Servo ground (often brown/black)Supply − and UNO GNDAll grounds share a reference

Disconnect power while wiring. Check pin labels and servo documentation rather than trusting wire color. Do not connect the external supply’s positive lead to the UNO 5 V pin while USB powers the board. An HC-SR04’s 5 V ECHO must be level-shifted for a 3.3 V board. This wiring and sketch are for a standalone UNO, not a robot-car shield.

  1. Upload: download the classroom-sonar Arduino sketch. Save it in a folder named classroom-sonar, open it in Arduino IDE, choose the UNO board and port, and upload. It uses the standard Servo library.
  2. Align: the sketch centers the servo at 90°. Disconnect power, mount the sensor facing forward, then reconnect. Confirm that 30° points right and 150° left. If reversed, set REVERSE_ANGLE = true. Avoid the servo’s mechanical stops.
  3. No servo? set USE_SERVO = false. Place the sensor over a protractor; the sketch prompts for each angle. Turn it by hand and send n when ready.
  4. Calibrate: open Serial Monitor at 9600 baud. Send s to take one scan. Compare the 90° reading with a ruler at 20, 50, and 100 cm. Repeat three times and record the spread before mapping.
  5. Collect: copy the angle/distance rows into the notebook below. The sketch takes three echoes per angle and reports their median only if all three are valid. NA means unknown; never turn a timeout into a zero-distance wall.
  6. Repeat: move to a second marked station, measure its x/y position and heading, and add its scan. Change one thing at a time: target material, angle spacing, or estimated position.

Echo math: distance in cm ≈ echo time in microseconds × 0.0343 ÷ 2. We divide by two because the sound travels to the object and back. The sketch waits at least 65 ms between pings and accepts 2–200 cm for this classroom experiment.

Troubleshoot: repeated NA → check pins, common ground, and a broad flat target. Board resets or a jittering servo → check the servo supply. Slanted walls can reflect sound away; cloth can weaken echoes. Two sensors pinging together can interfere, so run one station at a time or stagger scans.

Build support: ELEGOO kit downloads, Arduino servo wiring and power, and Arduino echo pulse timing.

Robot car: stop, scan, move, repeat

Gather: your assembled ELEGOO car or DIY chassis with a distance sensor, a taped course, ruler, and paper heading marks. Use the manufacturer’s example to verify the sensor and motors first. Car versions use different shields and pin assignments; do not upload the standalone scanner sketch unchanged.

  1. Make a small cardboard room and tape three stations 20–30 cm apart. Keep the car on the floor and the course clear.
  2. For the first map, move the car by hand between stations with its motors disabled. Stop completely to scan; record the sensor’s position, not just the wheel axle.
  3. Next, run a short low-speed drive between stations using your car’s own control example. Record the predicted motion and measure the actual displacement and heading.
  4. Plot identical scans twice: once with the predicted pose and once with the measured pose. Compare the mismatch at a wall seen from both stations.
  5. Return to the first station. Use a recognizable corner to correct the pose manually. Explain how this models the purpose of loop closure.

Extensions: wheel encoders estimate distance from turns (distance ≈ turns × wheel circumference); compare against a ruler to reveal slip. An IMU can help estimate turning, but a gyro’s bias also drifts. A line sensor can detect a taped checkpoint; it does not measure the distance to a room wall.

Limit: motor-on time is only a rough motion estimate, not measured wheel odometry. Autonomous SLAM needs a pose estimator and repeated scan matching or another correction method. Use ELEGOO’s V4.0 documentation only if that is your car version; find other versions in the download center.

From measurement to map

Your scan notebook

Paste a sensor scan or type tape-measure readings. Set the pose (position + heading) where the scan was taken, then add it to the plot. Add a second scan to see whether the walls line up. This draws measured endpoints and approximate beam paths, not a probabilistic occupancy grid.

Blue = first scan · orange = later scans · dot = possible surface · line = approximate sound path. Blank areas remain unknown.

Sensor pose (cm)

Origin is bottom left. x goes right, y goes up. Heading 0° faces up; positive headings turn left. Scan angle 90° faces forward.

Angles: 0–180°. Distances: 2–200 cm. Headers and # comments are accepted. NA is skipped.

No scans yet. Load an example or enter your measurements.

See endpoint coordinates
Notebook measurements (not saved after reloading)
ScanAngle °Range cmEndpoint xEndpoint y

Try a position error: add the example at x = 300. Change x to 325 and add the same readings again. The surfaces separate by 25 cm although the readings did not change. Clear the notebook and repeat with scans from two measured stations.

Math bridge: endpoint x = sensor x + distance × cos(heading + scan angle); endpoint y = sensor y + distance × sin(heading + scan angle). Convert degrees to radians when using code. A sonar echo can come from anywhere within its beam; the endpoint dot is a convenient approximation, not a pinpoint measurement.

Localization you can hold

Find the hidden station

Draw a known room map and mark four possible sensor stations with the same heading. The teacher chooses one and reports three tape-measure or sonar distances. Put a counter at every candidate station; predict the three readings from each position.

  1. Score: compare predicted and measured distances. Keep more counters at stations with smaller mismatches; allow a few centimeters of sensor error.
  2. Resample: make a new set of ten counters by copying well-matching stations more often. This is a simplified, discrete version of the particle filter.
  3. Move: announce a 20 cm move and shift each candidate position. Take a new scan to distinguish stations that initially looked alike.
  4. Kidnap: secretly choose a new station. Repeat with and without two fresh random guesses. Which group can recover?

Exit ticket: submit two scans with pose labels, a map showing free/occupied/unknown space, one repeated-measurement comparison, and a sentence explaining whether your activity performed mapping, localization, or full SLAM.

Sim 1 · Occupancy grid mapping

Paint the map with lasers

The robot wanders and scans ten times a second. Along each laser ray, cells the beam passed through get a vote for "free"; the cell where it stopped gets a vote for "wall." Votes add up, so one noisy reading can't ruin the map — but many consistent readings make a cell nearly certain. Click anywhere to send the robot there.

Keyboard: Tab into the map, move the crosshair with ←↑→↓ (Shift for bigger steps), and press Enter to send the robot.

  • Unknown
  • Free
  • Occupied
  • True robot
  • Where the robot thinks it is
LiDAR
Experiment

Try it

Drop the beams to 4. How long does the map take now? Then crank the noise to 25. Do the walls get fuzzier or just slower to appear?

Break it

Turn on drifting odometry. The orange robot is where the robot believes it is. Its map is drawn from that belief — watch the walls double and smear.

Explain it

The laser readings were fine in both runs. Why did the map still break? What would the robot need to notice to fix itself?

Sim 2 · Particle filter

A cloud of guesses

Now flip the problem: the robot has the map but has no idea where it is. A particle filter scatters hundreds of guesses (red dots) across the map. Each cycle it does three things:

  1. Move every guess the way the wheels say the robot moved, plus a little randomness.
  2. Score every guess: "If the robot were here, what would the laser see?" Guesses whose imagined scan matches the real scan score high.
  3. Resample: draw a new cloud, copying high scorers often and low scorers rarely.

Survival of the fittest guess. The yellow robot appears once the cloud agrees.

Keyboard: same as the mapping sim. Arrows move the crosshair, Enter sends the robot.

  • Particles (guesses)
  • True robot
  • Filter's best estimate
Filter

Small σ trusts the laser completely; big σ shrugs at mismatches.

Watch closely

Early on, the cloud often splits into two or three clumps. Those are places that look the same to the laser. Which rooms in the map are twins?

Kidnap

Press Kidnap robot with random guesses on, then again with them off. Why can't a filter with no fresh guesses recover?

Trust

Set σ to 4. The cloud collapses fast — sometimes onto the wrong spot. Overconfidence is a real engineering failure.

Engineer deep dive

Bayes' rule, twiceAges 15+

Occupancy as log-odds

Each cell stores ℓ = log( p / (1 − p) ). Bayes' rule for independent readings then becomes plain addition:

ℓt = ℓt−1 + log( p(occ | z) / p(free | z) ) − ℓ0

That is why the sim's map “votes”: a hit adds +0.9, a pass-through adds −0.4, and ℓ is clamped to ±5. The clamp keeps a cell able to change its mind when furniture moves.

The Bayes filter

bel⁻(xt) = ∫ p(xt | ut, xt−1) bel(xt−1) dxt−1
bel(xt) = η · p(zt | xt) · bel⁻(xt)

A Kalman filter solves this exactly when everything is Gaussian. A particle filter approximates bel with N weighted samples, so it can hold the multi-modal belief you see when the cloud splits into clumps.

Scoring a particle

With B beams, each predicted range r̂k and measured rk:

w ∝ Πk exp( −(rk − r̂k)² / 2σ² )

Multiply 12 small numbers and you underflow fast, so real code sums log-weights. Small σ makes the product razor-sharp. That is the overconfidence you see at σ = 4.

SLAM as optimization

Modern SLAM (graph SLAM, factor graphs) stores every pose as a node and every odometry step or scan match as a spring between nodes. Loop closure adds one more spring, and a least-squares solver relaxes the whole graph at once. Libraries like g2o, GTSAM, and Cartographer do this in real time.

Putting it together

How real SLAM fixes the smear

Sim 1 showed that mapping with a drifting position ruins the map. Sim 2 showed that matching scans to a map fixes the position. SLAM does both in a loop: it uses the map-so-far to correct its position, then uses the corrected position to extend the map.

Scan matching

Slide the new scan around until it lines up with the map built so far. The shift needed is the odometry error — subtract it.

Loop closure

When the robot returns somewhere it has been and recognizes it, it knows its whole path must bend to meet up. The entire map snaps straight.

Where you'll see it

Robot vacuums (LiDAR on top), Mars rovers, VR headsets tracking your room, phone AR apps, and self-driving cars all run some form of SLAM.

Next → Sensor Fusion: combine noisy wheels, gyros, and accelerometers into one good estimate

Where you’ll see it

Mapping robots in the real world

Click any photo to enlarge it.

Stanford’s Stanley, a blue Volkswagen SUV with sensors on its roof rack, at the 2005 DARPA Grand Challenge
Stanley, 2005 Stanford’s robot SUV won DARPA’s 132-mile desert race with no driver. Five laser scanners on the roof built a map of the road ahead, and a probabilistic filter tracked where the car was.Photo: DARPA · Public domain · Wikimedia Commons
A spinning Velodyne 64-beam LiDAR unit on a car roof
A spinning LiDAR This Velodyne unit fires 64 laser beams while it spins, measuring over a million distances a second. Our sim’s robot does the same job with 4–90 beams.Photo: Steve Jurvetson · CC BY 2.0 · Wikimedia Commons
A colorful top-down point cloud of a city intersection built from lidar scans
A map made of dots About 23 million LiDAR points from 18 seconds of driving, lined up into one map of a San Francisco intersection. Lining up scans like this is the “scan matching” step of SLAM.Photo: Daniel L. Lu · CC BY 4.0 · Wikimedia Commons
A grey Neato XV-11 robot vacuum with a round LiDAR turret on top
SLAM in your living room The Neato XV-11 robot vacuum has a small spinning laser under the raised bump on top. It maps rooms and cleans in neat rows instead of bouncing around at random.Photo: Autopilot · CC BY-SA 3.0 · Wikimedia Commons

Robot autonomy series

Sense · Think · Act

Quick check

Lock it in

1. A laser beam goes all the way across a square without stopping. What is that square?

2. Why does the map get smeary when the robot's wheels slip?

3. On the robot's map, what does gray mean?

1. Why is SLAM called a chicken-and-egg problem?

2. A laser beam travels 3 m before hitting a wall. What do the cells along the first 3 m get?

3. Why does odometry drift get worse over time?

4. In a particle filter, which guesses get copied most during resampling?