Arduino Ultrasonic Radar System with HC-SR04, Servo Motor and Processing IDE
An ultrasonic radar sweeps a distance sensor back and forth across a $180^\circ$ arc and plots nearby objects on a live sonar-style screen. It is an engaging project that combines servo positioning, acoustic time-of-flight measurement, and serial data visualization on a computer.

In this tutorial you will mount an HC-SR04 ultrasonic module onto an SG90 micro servo, write non-blocking sweep code on the Arduino Uno that formats angle and distance readings over USB serial, and render a glowing green sweep display in Processing IDE.
How the Ultrasonic Radar Works
The HC-SR04 measures distance by emitting a $40\text{ kHz}$ ultrasonic burst and timing how long the echo takes to bounce back from an obstacle. The SG90 servo rotates the sensor step-by-step from $15^\circ$ to $165^\circ$ and back again.
- The Arduino commands the SG90 servo to move to a specific angle $\theta$ and waits briefly for mechanical vibration to settle.
- A $10\text{ }\mu\text{s}$ HIGH pulse on the
TRIGpin fires eight ultrasonic cycles from the transmitter. - The
ECHOpin stays HIGH for the round-trip travel duration $t$ (in microseconds). - Using the speed of sound ($343\text{ m/s}$, or $0.0343\text{ cm/}\mu\text{s}$), the Arduino calculates one-way distance: $$\text{Distance (cm)} = \frac{t \times 0.0343}{2}$$
- The Arduino prints
angle,distance.over the USB serial port, which the Processing sketch parses to draw green lines for clear space and red lines where an object is detected.
Hardware and Settings
| Item | Choice | Reason |
|---|---|---|
| Microcontroller | Arduino Uno or Nano | $5\text{ V}$ I/O compatible with both HC-SR04 and SG90 servo |
| Distance Sensor | HC-SR04 Ultrasonic Module | Reliable range from $2\text{ cm}$ to $400\text{ cm}$ with $\sim 15^\circ$ beam angle |
| Servo Motor | SG90 $9\text{ g}$ Micro Servo | Lightweight, low current draw, and sweeps $0^\circ\text{--}180^\circ$ |
| Bracket | 3D-printed pan mount or hot-glue/zip-tie horn mount | Keeps the sensor level and centered over the servo shaft |
| Software | Arduino IDE + Processing 4 | Processing reads COM port data and renders $60\text{ FPS}$ 2D graphics |
Wiring Connections
Keep jumper wires flexible and give them enough slack so the servo horn can rotate freely across its full arc without tugging the sensor pins loose.
HC-SR04 and SG90 Servo to Arduino
| Component Pin | Arduino Pin | Notes |
|---|---|---|
HC-SR04 VCC | 5V | Ultrasonic transducer requires $5\text{ V}$ |
HC-SR04 GND | GND | Common ground |
HC-SR04 TRIG | D10 | Triggers $40\text{ kHz}$ ultrasonic burst |
HC-SR04 ECHO | D11 | Returns echo pulse duration |
SG90 VCC (Red) | 5V | Add a $100\text{ }\mu\text{F}$ capacitor across 5V and GND if the Arduino resets |
SG90 GND (Brown/Black) | GND | Common ground |
SG90 SIG (Orange/Yellow) | D9 | PWM control signal |
Complete Code
1. Arduino Sketch
#include <Servo.h>
#define TRIG_PIN 10
#define ECHO_PIN 11
#define SERVO_PIN 9
// Sweep bounds and step configuration
#define MIN_ANGLE 15
#define MAX_ANGLE 165
#define STEP_DEG 2
#define STEP_DELAY 30 // Milliseconds per step
// Timeout for ~100 cm max range (round-trip ~5800 us) to keep sweep smooth
#define ECHO_TIMEOUT_US 12000
Servo radarServo;
int measureDistanceCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long duration = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
if (duration == 0) {
return 0; // Out of range or no echo received
}
int distance = (duration * 0.0343) / 2.0;
return distance;
}
void sendReading(int angle) {
radarServo.write(angle);
delay(STEP_DELAY);
int dist = measureDistanceCm();
// Format expected by Processing parser: "angle,distance."
Serial.print(angle);
Serial.print(",");
Serial.print(dist);
Serial.print(".");
}
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
radarServo.attach(SERVO_PIN);
radarServo.write(MIN_ANGLE);
Serial.begin(9600);
delay(500);
}
void loop() {
// Sweep left to right
for (int angle = MIN_ANGLE; angle <= MAX_ANGLE; angle += STEP_DEG) {
sendReading(angle);
}
// Sweep right to left
for (int angle = MAX_ANGLE; angle >= MIN_ANGLE; angle -= STEP_DEG) {
sendReading(angle);
}
}
2. Processing Visualization Sketch
Paste this code into Processing IDE, update "COM3" (or "/dev/ttyACM0" on Linux) to match your Arduino port, and click Run
import processing.serial.*;
Serial myPort;
int iAngle = 0;
int iDistance = 0;
String rawData = "";
final int MAX_RANGE_CM = 40; // Radar outer ring distance in cm
void setup() {
size(1000, 600);
smooth();
// Print available serial ports in the console so you can verify your port name
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 9600);
myPort.bufferUntil('.');
background(0);
}
void draw() {
// Fade trail effect
noStroke();
fill(0, 12);
rect(0, 0, width, height - 50);
drawRadarGrid();
drawSweepLine();
drawDetectedObject();
drawHUD();
}
void serialEvent(Serial port) {
rawData = port.readStringUntil('.');
if (rawData != null) {
rawData = trim(rawData.substring(0, rawData.length() - 1));
int commaIndex = rawData.indexOf(',');
if (commaIndex > 0) {
iAngle = int(rawData.substring(0, commaIndex));
iDistance = int(rawData.substring(commaIndex + 1));
}
}
}
void drawRadarGrid() {
pushMatrix();
translate(width / 2.0, height - 60);
noFill();
strokeWeight(1.5);
stroke(30, 220, 60);
float maxRadius = width * 0.45;
for (int r = 1; r <= 4; r++) {
float d = (maxRadius * 2.0) * (r / 4.0);
arc(0, 0, d, d, PI, TWO_PI);
}
// Angle radial lines
for (int a = 30; a <= 150; a += 30) {
float rad = radians(a);
line(0, 0, -maxRadius * cos(rad), -maxRadius * sin(rad));
}
line(-maxRadius, 0, maxRadius, 0);
popMatrix();
}
void drawSweepLine() {
pushMatrix();
translate(width / 2.0, height - 60);
strokeWeight(4);
stroke(30, 250, 60);
float maxRadius = width * 0.45;
float rad = radians(iAngle);
line(0, 0, maxRadius * cos(rad), -maxRadius * sin(rad));
popMatrix();
}
void drawDetectedObject() {
if (iDistance > 0 && iDistance <= MAX_RANGE_CM) {
pushMatrix();
translate(width / 2.0, height - 60);
strokeWeight(6);
stroke(255, 40, 40);
float maxRadius = width * 0.45;
float pixDist = map(iDistance, 0, MAX_RANGE_CM, 0, maxRadius);
float rad = radians(iAngle);
float xStart = pixDist * cos(rad);
float yStart = -pixDist * sin(rad);
float xEnd = maxRadius * cos(rad);
float yEnd = -maxRadius * sin(rad);
line(xStart, yStart, xEnd, yEnd);
popMatrix();
}
}
void drawHUD() {
fill(0);
noStroke();
rect(0, height - 50, width, 50);
fill(30, 250, 60);
textSize(20);
text("Angle: " + iAngle + " deg", 40, height - 18);
String status = (iDistance > 0 && iDistance <= MAX_RANGE_CM) ? iDistance + " cm" : "Out of Range";
text("Distance: " + status, 260, height - 18);
text("Range: " + MAX_RANGE_CM + " cm", width - 200, height - 18);
}
Calibration and Testing
- Upload the Arduino sketch first and open the Serial Monitor at $9600\text{ baud}$. Confirm that comma-and-period-delimited pairs like
45,23.47,24.49,0.scroll smoothly across the screen, then close the Serial Monitor. - Open Processing IDE, paste the Java visualization code, and click Run. Check the bottom console to make sure
Serial.list()[0]matches your Arduino's COM port index (change[0]to[1]or[2]if needed). - Place a flat object—such as a book or box—about $20\text{ cm}$ in front of the sensor. You should see the green sweep beam turn red at the exact angle and radial ring corresponding to the object.
Common Problems
- Processing throws
Error opening serial portorPort busy: Only one program can access a COM port at a time. Close the Arduino IDE Serial Monitor or Serial Plotter before launching the Processing sketch. - Radar sweep stutters whenever nothing is in front of the sensor: Without a timeout parameter,
pulseIn()waits a full $1\text{ second}$ when no echo returns. KeepECHO_TIMEOUT_USset to12000so missed echoes return in $12\text{ ms}$. - Soft objects like curtains or clothing do not appear on screen: Fabric absorbs $40\text{ kHz}$ sound waves instead of reflecting them, and angled smooth surfaces deflect echoes away from the receiver. Test with flat, rigid surfaces facing the sensor.
- Servo jitters or resets the Arduino during direction reversals: USB ports on some laptops limit current when the servo reverses direction. Place a $100\text{ }\mu\text{F}$ to $470\text{ }\mu\text{F}$ electrolytic capacitor across the Arduino
5VandGNDrails.
Summary
Mounting an HC-SR04 onto an SG90 servo turns a stationary distance sensor into a wide-angle spatial scanner. Using a short pulseIn() timeout keeps the sweep fluid across $15^\circ\text{--}165^\circ$, while streaming angle,distance. packets over Serial allows Processing to render a real-time sonar display.