กลับหน้าหลัก
views
How to Connect ESP32 with HC-SR04 and Servo for Radar Project
Last updated on

How to Connect ESP32 with HC-SR04 and Servo for Radar Project


How to Connect ESP32 with HC-SR04 and Servo for Radar Project

This tutorial shows how to use ESP32 with HC-SR04 ultrasonic sensor and SG90 servo motor to build a simple object-detecting radar. Perfect for beginners who want to do something practical with ESP32 beyond blinking LEDs.

Required Components

  • ESP32 board (NodeMCU ESP32 or ESP32 DevKit)
  • HC-SR04 Ultrasonic Sensor
  • SG90 Servo Motor 0-180 degrees
  • Breadboard 830 points
  • Jumper wires (male-male, male-female, female-female)
  • Micro USB cable for code upload
  • 5V 2A Power Adapter (optional for stable power)

Wiring Diagram: ESP32 with HC-SR04 and Servo

Connect HC-SR04 to ESP32

ESP32 GPIOHC-SR04
VIN (5V)VCC
GNDGND
GPIO 22Trig
GPIO 23Echo

Connect Servo Motor to ESP32

ESP32 GPIOSG90 Servo
VIN (5V)Red Wire (VCC)
GNDBlack/Brown Wire (GND)
GPIO 21Orange Wire (Signal)
Circuit diagram showing ESP32 connected to HC-SR04 and Servo on breadboard with clear wire colors

Install Servo Library for ESP32

ESP32 requires an additional servo library since the standard Arduino Servo library doesn’t work well with it:

  1. Download ESP32 Servo Library
  2. Extract and place the folder in Documents/Arduino/libraries/
  3. Restart Arduino IDE

Arduino Code: Read Distance from HC-SR04

// Define GPIO pins
const int TRIG_PIN = 22;
const int ECHO_PIN = 23;

void setup() {
  Serial.begin(115200);
  
  // Set Trig pin as Output
  pinMode(TRIG_PIN, OUTPUT);
  // Set Echo pin as Input
  pinMode(ECHO_PIN, INPUT);
}

void loop() {
  // Send ultrasonic pulse
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  
  // Measure echo pulse duration
  long duration = pulseIn(ECHO_PIN, HIGH);
  
  // Convert to centimeters (speed of sound = 343 m/s)
  // Use / 58 for centimeters
  float distance = duration / 58.0;
  
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  delay(500);
}

Complete Radar Code for ESP32

#include <ESP32Servo.h>

// Define GPIO pins
const int TRIG_PIN = 22;
const int ECHO_PIN = 23;
const int SERVO_PIN = 21;

// Servo variables
Servo myServo;
int servoAngle = 0;
int servoDirection = 1;

// Radar variables
const int SCAN_MIN_ANGLE = 15;
const int SCAN_MAX_ANGLE = 165;
const int MAX_DISTANCE = 100;  // Maximum scan range (cm)

void setup() {
  Serial.begin(115200);
  
  // Setup HC-SR04 pins
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  
  // Setup Servo
  myServo.attach(SERVO_PIN);
  myServo.write(90);  // Start at 90 degrees
  
  delay(1000);
}

void loop() {
  // Move servo in increments
  servoAngle += servoDirection * 2;
  
  // Reverse direction at limits
  if (servoAngle >= SCAN_MAX_ANGLE) {
    servoDirection = -1;
  } else if (servoAngle <= SCAN_MIN_ANGLE) {
    servoDirection = 1;
  }
  
  // Move servo to position
  myServo.write(servoAngle);
  
  // Measure distance
  float distance = measureDistance();
  
  // Send data as: angle,distance
  Serial.print(servoAngle);
  Serial.print(",");
  Serial.println(distance);
  
  delay(50);  // Wait for servo to reach position
}

float measureDistance() {
  // Send ultrasonic pulse
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  
  // Measure echo return time
  long duration = pulseIn(ECHO_PIN, HIGH, 25000);  // 25ms timeout
  
  // No echo means object is beyond range
  if (duration == 0) {
    return MAX_DISTANCE;
  }
  
  // Convert to centimeters
  float distance = duration / 58.0;
  
  // Cap at MAX_DISTANCE
  if (distance > MAX_DISTANCE) {
    return MAX_DISTANCE;
  }
  
  return distance;
}

Display Radar on Processing

To see a real radar display, use Processing IDE to draw the radar screen. The Arduino code sends angle and distance data via Serial in format angle,distance.

How Processing Code Works

  1. Read data from Serial Port
  2. Parse angle and distance values
  3. Draw a line from center at the given angle
  4. The distance becomes a point on that line
  5. Detected objects appear as red dots on the radar screen

What to Modify in Processing Code

  • Serial COM port must match your board’s port (e.g., COM3 or /dev/ttyUSB0)
  • Match baud rate with Arduino code (115200)
  • Adjust colors and screen size as needed
Processing radar display showing sweeping line with detected object dots in red on dark background

Troubleshooting Common Issues

HC-SR04 Reads Incorrect Values

  • Verify VCC receives proper 5V (ESP32 VIN supplies 5V)
  • If using USB power alone, there may be insufficient power; try external adapter
  • Increase delay between measurements to avoid reading too frequently

Servo Not Moving or Jittering

  • Add 100uF capacitor across Servo power pins to smooth power
  • Ensure Servo GND connects to ESP32 GND
  • For high power servos, use external 5V power supply instead

Serial Monitor Shows No Output

  • Check baud rate is set to 115200
  • Press EN button on ESP32 board to reset if needed
  • Verify USB cable works properly
SG90 servo with HC-SR04 attached to rotating arm showing degree markings

How HC-SR04 Ultrasonic Sensor Works

HC-SR04 uses sonar principle similar to bat navigation:

  1. Emit ultrasonic pulse at 40kHz
  2. Measure time for pulse to return after bouncing off objects
  3. Calculate distance using formula: distance = (speed of sound × time) / 2

Speed of sound in air is approximately 343 m/s. Converting to cm/μs gives 0.0343, which is why we use duration / 58 in the code.

Summary

This project combines ultrasonic distance sensing and servo motor control into a scanning radar system. To expand this project, consider adding:

  • SD card data logging
  • OLED/LCD display output
  • Buzzer alarm for nearby objects
  • Improved Processing visualization

Reference Video

https://www.youtube.com/embed/U8-B_t64ZrI

อยากทำโปรเจคแบบนี้?

รับทำโปรเจค Arduino / IoT จบงานไว ส่งงานครบ พร้อมสอน

If you need Arduino project service or urgent IoT development, see full service details on the home page

จ้างทำโปรเจคเลย

ความคิดเห็น

Verified user reviews

รีวิวและความคิดเห็นจากผู้ใช้จริง

ล็อกอินด้วยบัญชีบนเว็บนี้แล้วให้คะแนนหรือคอมเมนต์ได้เลย ระบบเก็บผ่าน Supabase ไม่ต้องใช้ GitHub แล้ว

กำลังโหลดรีวิว...