Build a Working Radar: Mapping Rooms with Arduino, Ultrasnonics, and Servos

Build a Working Radar: Mapping Rooms with Arduino, Ultrasnonics, and Servos


📑Table of Contents
What You'll Need 5 items
Arduino Uno R3
Buy
HC-SR04 Ultrasonic Sensor
Buy
SG90 Micro Servo
Buy
Breadboard
Buy
Jumper Wires
Buy

Affiliate links help support this site at no extra cost to you.

Welcome to Day 23. We have reached a major milestone. For the past 22 days, we have learned isolated skills.

  • Day 21: We learned how to see distance (Input).
  • Day 22: We learned how to move precisely (Output).
  • Day 13: We learned about Arrays and Loops (Logic).

Today, we combine them. We are not just blinking an LED. We are building a System. We are building a Scanning Radar Station. This project mimics the technology used in submarines (SONAR) and airports (RADAR). It will physically sweep a sensor back and forth, map the room, and send that data to your computer to generate a visual map of the invisible world.

Processing Radar UI Concept

The Mission: What are we building?

We are building a device that:

  1. Rotates an HC-SR04 sensor from 0 to 180 degrees.
  2. At every degree, it stops and pings the distance.
  3. It calculates the coordinates of any obstacle.
  4. It visualizes this “Point Cloud” on a screen.

The Problem: Single Point vs. Scanning

Yesterday, our sensor was a “flashlight”. It only saw what was directly in front of it. If a wall was to the left, the robot was blind to it. By mounting the sensor on a Servo, we turn that flashlight into a Lighthouse. We gain a 180-degree Field of View (FOV).

The Hardware Build

This is our most complex build yet. You will need:

  1. Arduino Uno.
  2. HC-SR04 Ultrasonic Sensor.
  3. SG90 Servo Motor.
  4. Breadboard & Jumper Wires.
  5. Important: A way to mount the sensor on the servo.

The Mount

You can 3D print a bracket, or use the “Maker’s Glue”: Double Sided Tape. Stick the HC-SR04 directly onto the plastic horn of the servo. Ensure the servo can rotate freely without the wires getting tangled.

Project Assembly Render

The Wiring

We are combining the wiring from Day 21 and Day 22. CRITICAL: We now have TWO power-hungry devices. The Servo draws current when moving. The Sensor draws current when pinging. If you try to power both from the Arduino 5V pin, you might get Noise or Brownouts.

  • Best Practice: Use an external 4xAA battery pack (6V) to power the Servo. Connect the Battery GND to Arduino GND (Common Ground).
  • Good Practice: Use a 470uF Capacitor on the power rails.

Pinout:

  • Servo Signal: Pin 9.
  • Sensor Trig: Pin 10.
  • Sensor Echo: Pin 11.

Wiring Diagram Complete

The Math (Polar Coordinates)

This is where High School Math finally becomes useful. The sensor gives us two numbers:

  1. Theta (θ\theta): The Angle of the servo (e.g., 45 degrees).
  2. Radius (r): The Distance to the object (e.g., 50 cm).

This is called the Polar Coordinate System. But computers screens (and graph paper) use the Cartesian Coordinate System (X, Y). To plot a dot on the screen, we need to convert Polar to Cartesian.

The Formula:

  • X=r×cos(θ)X = r \times \cos(\theta)
  • Y=r×sin(θ)Y = r \times \sin(\theta)

Note: Arduino’s sin() and cos() functions expect Radians, not Degrees. We must convert using the radians() helper.

Polar Coordinate Math Infographic

The Arduino Code

We need a loop that:

  1. Moves to Angle 0.
  2. Waits for the servo to settle.
  3. Pings distance.
  4. Prints “Angle,Distance” to the Serial Monitor.
  5. Increases Angle.
  6. Repeats until 180.
  7. Sweeps back.
#include <Servo.h>
#include <NewPing.h>

#define TRIG_PIN 10
#define ECHO_PIN 11
#define MAX_DIST 200 // Max distance 200cm

Servo radarServo;
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DIST);

void setup() {
  Serial.begin(9600); // Fast communication
  radarServo.attach(9);
}

void loop() {
  // Sweep from 15 to 165 degrees
  // We avoid 0 and 180 as they often stretch the wires too much
  for (int i = 15; i <= 165; i++) {
    radarServo.write(i);
    delay(30); // Speed of rotation. Smaller = Faster
    
    // Calculate distance
    int distance = sonar.ping_cm();
    
    // Print for the Plotter: "Angle,Distance"
    Serial.print(i); 
    Serial.print(","); 
    Serial.println(distance);
  }
  
  // Return Sweep
  for (int i = 165; i >= 15; i--) {
    radarServo.write(i);
    delay(30);
    int distance = sonar.ping_cm();
    Serial.print(i);
    Serial.print(",");
    Serial.println(distance);
  }
}

Advanced Physics: The Speed Limit of Scanning

Why did I use delay(30)? Can we go faster? Let’s do the math.

  1. Speed of Sound: 343 m/s (34,300 cm/s).
  2. Max Distance: 200 cm (Round trip = 400 cm).
  3. Time of Flight: 400/34300=0.011400 / 34300 = 0.011 seconds (11 ms). If we ping every 5 ms, the previous echo might return while we are listening for the current ping. This creates “Ghost echoes”. We must wait at least 20-30 ms between pings to let the air “clear”. Maximum Scan Rate:
  • 30ms per degree x 180 degrees = 5400 ms (5.4 seconds per sweep). If you scan faster, your data becomes garbage. Physics has a speed limit.

Hacker’s Corner: Non-Blocking Radar (millis())

The code above uses delay(), which freezes the Arduino. If you want your robot to drive while scanning, you must use millis(). We will master this in Phase 5, but the concept is:

  1. Check currentMillis.
  2. If 30ms has passed since lastPingTime:
  3. Move Servo 1 degree.
  4. Ping.
  5. Update lastPingTime. This allows the loop() to run thousands of times per second, checking other sensors in between radar pings.

Visualization (The Serial Plotter)

Upload the code. Open Tools > Serial Plotter. You won’t see a Radar Map yet. You will see a temporal graph.

  • Red Line: The Angle (Triangle Wave, going up and down).
  • Blue Line: The Distance (The “Landscape” of your room). If you put a box in front of the radar, the Blue line will dip (short distance) when the Red line (Angle) crosses the box’s position. It is an abstract view, but it proves the data is real.

Serial Plotter Output

Deep Dive: How the Serial Plotter Works

The Serial Plotter is a “dumb” tool. It listens for numbers separated by commas or spaces.

  • Serial.println(50); -> Draws 1 line at Y=50.
  • Serial.print(10); Serial.print(","); Serial.println(50); -> Draws 2 lines (Y=10, Y=50).
  • The Legend: The colors are auto-assigned (Blue, Red, Green, Orange).
  • The Y-Axis: Auto-scales to fit your data.
  • The X-Axis: Is just “Time” (Sample Number). It is not “Angle”. This is why we cannot draw a true Radar Circle inside the Arduino IDE. The Plotter only does Time-Series graphs (like an Oscilloscope). To get X/Y mapping, we NEED external software.

Deep Dive: Data Flow and Processing

How do we get the “Cool Sci-Fi Radar Screen” (like the first image)? The Arduino cannot display complex graphics. We need to offload the rendering to a powerful computer. Data Flow Architecture:

  1. Sensor gathers raw physics data.
  2. Arduino packages it into a protocol (Angle,Distance\n).
  3. USB Cable transmits it via UART.
  4. PC Application (written in Python, Processing, or Unity) reads the stream and draws the pixels.

Data Flow Diagram

The Processing Language

For years, the go-to tool for Arduino visualization has been Processing. It is a Java-based coding environment built for visual arts. It has a Serial library that can read the Arduino’s output. Writing a Processing sketch to draw a fading green radar line is a classic project. We will cover Processing in depth in Phase 6 (Interfacing).

Hacker’s Corner: The “Processing” Code Logic

Even though we haven’t learned Processing yet, here is the logic you would write in Java:

  1. Setup: Create a window 800x600. Black background.
  2. Draw Loop:
    • Fade the background slightly (draw a semi-transparent black rectangle over everything). This creates the “Phosphor Fade” trail effect.
    • Read the Serial Port (Angle, Distance).
    • Convert Polar to Cartesian (X, Y).
    • Draw a Green Line from Center to Edge (The Sweep).
    • If Distance < Max: Draw a Red Dot at (X, Y). This logic creates that classic movie radar look where old contacts slowly fade away.

Advanced Physics: LIDAR vs SONAR vs RADAR

Why did we use Sound? Why not Light?

  • SONAR (Sound Navigation and Ranging): Uses Sound. Good for water and simple robotics. Slow speed of sound limits refresh rate. Wide beam (poor resolution).
  • LIDAR (Light Detection and Ranging): Uses Lasers. Extremely fast. Extremely narrow beam (Pinpoint accuracy). Used in Self-Driving Cars and iPhones.
  • RADAR (Radio Detection and Ranging): Uses Radio Waves. Can see through clouds and rain. Used by airports and military.

For a hobby robot, Ultrasonic is cheap and easy. But its Beam Width (15 degrees) means everything appears blurry and larger than it is.

Science Class: The Speed of Sound and Temperature

We treat the Speed of Sound as a constant (343 m/s). But in Day 21, we learned it changes with air temperature. In a Radar application, accuracy matters. Speed=331.3+(0.606×Temperature)Speed = 331.3 + (0.606 \times Temperature).

  • AT 0°C (Freezing): 331.3 m/s.
  • AT 20°C (Room Temp): 343.4 m/s.
  • AT 40°C (Hot Desert): 355.5 m/s. This is a 7% difference. If your radar says an object is at 100cm in a cold room, it might actually be at 107cm in a hot room. Professional sonar systems (like on submarines) constantly measure water temperature and salinity to correct their math. You can add a DHT11 temperature sensor (Phase 3) to your Radar Bot to make it biologically accurate!

LIDAR vs SONAR Comparison

Project Extension: The Stealth Fighter Experiment

Try this experiment:

  1. Place a flat book standing up in front of your radar. The sensor sees it clearly.
  2. Now, Angle the book back by 45 degrees.
  3. The sensor will likely map “Infinity” (No obstacle). Why? The sound wave hits the angled book and bounces Up towards the ceiling, never returning to the Echo pin. This is exactly how Stealth Aircraft (like the F-117 Nighthawk) work. They don’t absorb radar; they deflect it away from the receiver. You just built a Stealth Technology demonstrator on your desk.

Stealth Technology Diagram

Power Management: The Common Ground Issue

I mentioned this in the wiring section, but it is the #1 cause of failure in this project. If you use a battery for the servo and USB for the Arduino… YOU MUST CONNECT THE NEGATIVE TERMINALS TOGETHER. Electricity needs a return path. Without a Common Ground, the Servo Signal (which is relative to Arduino Ground) means nothing to the Servo (which is relative to Battery Ground). The servo will jitter or do nothing. Always tie the grounds.

Power Distribution Schematic

Troubleshooting: Ghost Echoes and Crosstalk

In a real room, you might see “Ghost Objects” that don’t exist. Why?

  1. Multi-path Propagation: The sound hits a wall, bounces to a table, bounces to the sensor. The sensor thinks the wall is further away than it is.
  2. Crosstalk: If you have TWO robots, Robot A might hear Robot B’s ping.
  3. Soft Objects: Curtains and carpets absorb sound. They become “Invisible” to sonar. The Fix for Noise: Average your readings. Instead of 1 ping per degree, take 3 pings and average them. It slows down the sweep, but increases reliability.

History: The Battle of Britain

Radar (Radio Detection and Ranging) changed the world in 1940. The Royal Air Force (RAF) built a chain of radar towers (“Chain Home”) along the coast. They could see German bombers gathering over France, 100 miles away. This allowed the RAF to scramble their Spitfires exactly where they were needed, instead of patrolling randomly. It was the first time in history that humans extended their vision beyond the horizon. Your little robot is a tribute to that technology.

Physics Deep Dive: Absorption and Reflection

Why can’t our robot see the carpet? Sound behaves like light.

  • Specular Reflection: When sound hits a smooth, hard surface (wall, book, plastic), it bounces off efficiently like a mirror.
  • Diffuse Reflection: When sound hits a rough surface (carpet, wool, foam), it scatters in all directions. Very little returns to the sensor.
  • Absorption: Soft materials convert sound energy into heat (vibration). The echo is too weak to be heard. Stealth Engineering: If you want to make your robot invisible to other radar bots, wrap it in felt or cotton wool!

Future Upgrades: Making it Standalone

Right now, you need a PC to see the map. How can we make it portable?

  1. Add an LCD Screen (Day 20): You can print “Target Detected: 30cm” on the 16x2 display.
  2. Add a Buzzer (Day 16): Make it beep faster as objects get closer (like a car parking sensor).
  3. Add Wheels (Day 17): If the path is clear (Distance > 50cm), drive forward. If not, turn left. This is the basis of Obstacle Avoidance Robots.

The Engineer’s Glossary (Day 23)

  • Polar Coordinate: A system defining a point by Distance and Angle.
  • Cartesian Coordinate: A system defining a point by X and Y.
  • Point Cloud: A collection of data points in space representing a 3D shape.
  • FOV (Field of View): The angular extent of the observable world (180 degrees for our servo).
  • UART (Universal Asynchronous Receiver-Transmitter): The hardware protocol used by simple Serial communication.

Conclusion

You have built a perceive-act system. Your Arduino is no longer just blinking; it is sensing spatial data. This represents the end of the “Components” phase. We have covered Input (sensors), Output (displays, motors), and Logic.

Next, we start Advanced Communication. We are going to learn how chips talk to each other.

  • I2C: The 2-wire network.
  • SPI: The high-speed data hose.
  • UART: The classic serial.

See you on Day 24, where we will learn the language of chips: I2C Protocol.

Comments