Bat Vision: Build a Collision-Proof Robot with Arduino Ultrasonic Sensors

Bat Vision: Build a Collision-Proof Robot with Arduino Ultrasonic Sensors


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

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

Welcome to Day 21. We have entered Phase 4. For the past 20 days, we have built a solid foundation.

  • We mastered Electronics (Voltage, Current, Resistance).
  • We mastered Components (Transistors, Relays, LEDs).
  • We mastered Signals (Digital, Analog, PWM).

Now, we shift our focus to Perception. A robot that cannot see is just a remote-controlled car. To be autonomous, a machine must understand its environment. It needs to answer the question: “How far away is that wall?”

Today, we are going to give your Arduino Bat Vision. We are going to use the HC-SR04 Ultrasonic Sensor. It uses sound waves to measure distance with millimeter precision. It is the standard “Eye” for every beginner robot, but to master it, you need to understand the physics of sound.

Robot Perception POV

The Physics: How to See with Sound

Humans see with light (Photons). Bats and Dolphins see with sound (Sonar). SoNAR stands for Sound Navigation And Rranging.

The concept is simple:

  1. Scream really loud.
  2. Start a stopwatch.
  3. Wait for the echo to come back.
  4. Stop the stopwatch.

Since we know the speed of sound, we can calculate the distance. Distance = (Speed * Time) / 2. Why divide by 2? Because the sound has to travel to the wall AND back. We only want the distance to the wall.

Sonar Physics Diagram: Ping and Echo

The Hardware: The HC-SR04

This iconic module looks like a pair of robot eyes. But they aren’t eyes. They are speakers.

  • Left Cylinder (T): Examples the Transmitter. It blasts a 40kHz Ultrasonic Burst.
  • Right Cylinder (R): The Receiver. It is a tiny microphone tuned to 40kHz.
  • The Crystal: In the back, a crystal controls the precise timing.

Why 40kHz? Human hearing ranges from 20Hz to 20,000Hz (20kHz). 40kHz is “Ultra” sonic. We cannot hear it. This is good, because otherwise your robot would be screaming constantly.

The Pinout

It has 4 pins.

  1. VCC: 5V Power.
  2. Trig (Trigger): Input. We pulse this to say “Fire!”
  3. Echo: Output. This pin goes HIGH for exactly as long as the sound is in the air.
  4. GND: Ground.

HC-SR04 Pinout Macro

Math Class: The Speed of Sound

To measure distance, we need a constant. The Speed of Sound in dry air at 20°C is 343 meters per second. Or: 0.0343 centimeters per microsecond.

So, the formula for our code will be: Distance (cm) = Duration (microseconds) * 0.0343 / 2

Simplifying the math: Distance (cm) = Duration / 58.2 (Most people round this to roughly Duration / 29 for the one-way trip).

Speed of Sound Formula Visualization

The Code Concept: pulseIn()

How do we measure “Microseconds” on Arduino? We use a special command: pulseIn(pin, HIGH). This function pauses the Arduino.

  1. It waits for the pin to go HIGH.
  2. It starts a timer.
  3. It waits for the pin to go LOW.
  4. It stops the timer and returns the length in microseconds.

It is perfectly designed for the HC-SR04 Echo pin.

Pulse Timing Diagram

Project 1: The Serial Distance Meter

Let’s build a tape measure. Wiring:

  1. VCC -> 5V.
  2. GND -> GND.
  3. Trig -> Pin 9.
  4. Echo -> Pin 10.

The Code:

const int trigPin = 9;
const int echoPin = 10;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT); // Echo sends data TO us
  Serial.begin(9600);
}

void loop() {
  // 1. Clear the Trig Pin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // 2. Fire the "Ping" (10 microsecond pulse)
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // 3. Listen for the Echo
  // result is time in microseconds
  long duration = pulseIn(echoPin, HIGH);

  // 4. Calculate Distance
  // Speed of sound = 343m/s = 0.0343 cm/us
  int distanceCm = duration * 0.0343 / 2;

  // 5. Print
  Serial.print("Distance: ");
  Serial.print(distanceCm);
  Serial.println(" cm");

  delay(100); // Don't ping too fast!
}

Upload it. Open Serial Monitor. Put your hand in front of the sensor. Move it back and forth. You should see the numbers change in real-time.

Breadboard Wiring Render

Deep Dive: The 10 Microsecond Rule

Why did we do that weird HIGH/LOW dance at the start? digitalWrite(trigPin, HIGH); delayMicroseconds(10); The HC-SR04 has a microchip on board. It sleeps until it receives a “Wake Up” pulse on the Trig pin. The datasheet says this pulse must be at least 10 microseconds long. If you just click it ON and OFF instantly, the sensor ignores you. You have to hold the button down for 10us. Once it wakes up, it automatically fires 8 pulses of 40kHz sound (the “Sonic Burst”).

Professional Upgrade: The NewPing Library

The manual code above is good for learning, but bad for multitasking. pulseIn() pauses your entire robot. It freezes the brain. For advanced robots, we use the NewPing library (by Tim Eckel). It is faster, more accurate, and can ping multiple sensors without freezing the code.

#include <NewPing.h>

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

This library handles all the physics math for you. It also fixes the “Zero” error when no echo is received. However, for this week, stick to the manual method so you understand the raw physics first.

Project 2: The Reverse Parking Sensor

Reading numbers is boring. Let’s build a car reversing aid. beep… beep… beep.. beep.beep.beep! Add Components:

  • Piezo Buzzer on Pin 11 (Passive or Active).
  • LED on Pin 13 (Optional).

The Logic:

  • Distance > 100cm: Silent.
  • Distance 50-100cm: Slow Beep.
  • Distance 10-50cm: Fast Beep.
  • Distance < 10cm: Continuous Scream.
int buzzerPin = 11;

void loop() {
  // ... (Calculation Code from Project 1) ...
  
  if (distanceCm < 10) {
    // CRITICAL: Scream
    tone(buzzerPin, 1000); 
  } 
  else if (distanceCm < 50) {
    // DANGER: Fast Beep
    tone(buzzerPin, 1000);
    delay(50);
    noTone(buzzerPin);
    delay(distanceCm * 2); // Dynamic delay!
  }
  else if (distanceCm < 100) {
    // WARNING: Slow Beep
    tone(buzzerPin, 1000);
    delay(100);
    noTone(buzzerPin);
    delay(500);
  }
  else {
    // SAFE: Silence
    noTone(buzzerPin);
    delay(100);
  }
}

Notice the trick: delay(distanceCm * 2). As the distance gets smaller, the delay gets shorter. The beeping naturally speeds up as you get closer. This is Algorithmic Audio.

Schematic: Parking Sensor Project

The Limitations: Blind Spots and Fluff

The HC-SR04 is magical, but it is not perfect. Bat vision has flaws.

  1. Soft Surfaces: If you aim it at a pillow or a curtain, the sound is absorbed. No echo returns. The sensor thinks the distance is infinite.
  2. Angles: If you aim it at a wall at a 45-degree angle, the sound bounces OFF the wall and away from you (like a pool ball). No echo returns.
  3. The “Close Range” Blind Spot: The sensor cannot see anything closer than 2cm. The sound comes back too fast for it to switch from “Transmit” to “Receive” mode.
  4. Interference: If you have two robots facing each other, Robot A might hear Robot B’s ping and get confused (Crosstalk).

Blind Spot Illustration

Science Class: Temperature Compensation

Remember the number 343 m/s? That is only true at 20°C. Sound travels faster in warm air and slower in cold air. Formula: V=331.3+(0.606Temp)V = 331.3 + (0.606 * Temp).

  • At 0°C (Freezing), speed is 331 m/s.
  • At 40°C (Desert), speed is 355 m/s.

This is a 7% Error. If you are building a precision instrument, you need to add a Thermistor (Day 16) to measure the air temperature and adjust your math dynamically. For a parking sensor? It doesn’t matter. But for a lab experiment, it is critical.

Advanced Project: The Radar Screen

What if we mounted the sensor on a Servo motor? And we swept it back and forth? We could map the entire room. We could send the data (Angle, Distance) to the PC. Using a program like Processing or Python, we can draw a green radar sweep screen. This is called LIDAR (if using light) or Sonar Mapping. We will build this in Week 8.

Radar Screen Concept Art

History: The Titanic and the invention of Sonar

Who invented this technology? It wasn’t for robots. It was for war and icebergs. After the Titanic sank in 1912, the world realized we needed a way to see underwater. In 1915, French physicist Paul Langevin invented the first active sonar to detect submarines during WWI. He used quartz crystals (Piezoelectricity!) to generate sound waves in water. Today’s HC-SR04 uses the exact same piezoelectric principle, just in air instead of water. From hunting U-Boats to parking your Toyota Prius, the tech hasn’t changed much in 100 years.

Hardware Deep Dive: Waterproof Variants (JSN-SR04T)

The HC-SR04 has a fatal flaw. It has open mesh speakers. If it rains, it dies. If you are building an outdoor rover or a boat, you need the JSN-SR04T. It looks like a car’s reverse parking sensor (black, sealed, waterproof).

  • Pros: Waterproof, longer cable.
  • Cons: Blind spot is larger (25cm vs 2cm). It uses the exact same code! You can unplug an HC-SR04 and plug in a JSN-SR04T and it just works.

Ethics and Safety: Please Respect the Dog

A final warning about “Ultrasonic”. We cannot hear 40kHz. Dogs can. (Up to 45kHz). Cats can. (Up to 64kHz). Bats can. (Up to 110kHz). If you build a robot that is constantly screaming at 40kHz 24/7, you might drive your pets insane. They might leave the room or bark at the robot. Rule: Only ping when you need to. Don’t leave the sensor running while you sleep if your dog sleeps in the same room. Be a kind engineer.

Deep Dive: The 3-Pin vs 4-Pin Sensor

You might buy a sensor that has only 3 pins (VCC, GND, SIG). This is the Ping))) sensor style (popularized by Parallax). It uses the SAME pin for Trigger and Echo.

  1. Set Pin to OUTPUT. Fire Trigger.
  2. Set Pin to INPUT. Listen for Echo. It saves an Arduino pin, but the code is slightly more complex. The usage is identical otherwise. Just be aware when buying: HC-SR04 (4-pin) is cheaper and easier for beginners.

Troubleshooting Guide

  1. Reads “0cm” constantly?
    • Check wiring. VCC and GND might be loose.
    • Check blind spot. Are you closer than 2cm?
    • Sensor might be “Locked”. Sometimes the Echo pin gets stuck HIGH. Unplug VCC and plug it back in to reset the internal chip.
  2. Reads “3000cm”?
    • The pulse timed out. The sound never came back. You are aiming at empty space or a soft fabric.
  3. Jittery Numbers?
    • Sound bounces around corners.
    • Use the Average technique (Day 16) to smooth the data.

The Bill of Materials (BOM)

ComponentQuantityValueNotes
Arduino Uno1AnyThe Brain
HC-SR041Ultrasonic ModuleThe Sensor
Buzzer1Passive/ActiveThe Alarm
Jumper Wires4M-FMale-to-Female for the sensor
Breadboard1HalfPrototyping

The Engineer’s Glossary (Day 21)

  • Ultrasonic: Sound frequency above 20kHz (Hearing limit).
  • Transducer: A device that converts measuring energy (Electricity -> Sound).
  • Sonar: Sound Navigation and Ranging.
  • TOF (Time of Flight): Measuring distance by timing a pulse.
  • Echo: The reflection of the sound wave.
  • PulseIn: Arduino function to measure pulse width.

Conclusion

You have given your machine a sense of space. Before today, your robot existed in a void. Now, it knows if it is about to crash. It knows if a human is walking by. It has spatial awareness.

This sensor is the cornerstone of the Obstacle Avoiding Robot, which is our final boss project. But an eye is useless without a body. To make a robot meaningful, we need to move. We learned DC Motors (Day 17), but they are dumb. They just spin. We need precision motion. We need to move exactly 90 degrees. We need the Servo Motor.

Tomorrow, on Day 22, we master the Servo. We will build a robotic arm that can wave hello.

See you on Day 22.

Comments