Radar 4

By Paul , 15 September 2025

Simple Arduino Radar with Processing - Step by Step Guide

Why This Approach is Much Easier

Only 3 components - Arduino Mega, servo, ultrasonic sensor
No complex TFT display wiring - uses your computer screen instead
Easy troubleshooting - see data in real-time
Professional radar display - looks just as good as TFT version
Works on any computer - no special hardware needed


Components Needed (Only 3!)

ComponentPurposeNotes
Arduino Mega 2560Main controllerAny Arduino Mega will work
HC-SR04 Ultrasonic SensorDistance measurementVery common, cheap sensor
SG90 Servo MotorRotates the sensorStandard 9g servo
Jumper wiresConnectionsMale-to-male, about 10 wires
USB cableArduino connectionUsually comes with Arduino

Total cost: About $20-25


Super Simple Wiring (Only 6 Wires!)

Arduino Mega Pin Connections

ComponentWire ColorArduino Pin
Servo  
Red (Power) 5V
Brown/Black (Ground) GND
Orange (Signal) Pin 6
Ultrasonic Sensor  
VCC (Power)Red5V
GND (Ground)BlackGND
TRIG (Trigger)Any colorPin 9
ECHO (Echo)Any colorPin 10

Visual Wiring Guide

Arduino Mega
┌─────────────────┐
│  ╔═══════════╗  │
│  ║ USB PORT  ║  │     Servo Motor
│  ╚═══════════╝  │     ┌─────────┐
│                 │     │  ┌───┐  │
│  Pin 6  ────────┼─────┤  │ ● │  │ ← Ultrasonic mounted here
│  Pin 9  ────────┼───┐ │  └───┘  │
│  Pin 10 ────────┼─┐ │ └─────────┘
│  5V     ────────┼─┼─┼─── Red wires (Power)
│  GND    ────────┼─┼─┼─── Black wires (Ground)
└─────────────────┘ │ │
    Ultrasonic      │ │
    ┌─────────────┐ │ │
    │ TRIG ECHO   │ │ │
    │  │    │     │ │ │
    │  └────┼─────┘ │ │
    │       └───────┘ │
    └─────────────────┘

Step 1: Physical Assembly (15 minutes)

Mount Ultrasonic Sensor to Servo

  1. Attach the ultrasonic sensor to the servo horn (white plastic piece)
  2. Use small screws or strong double-sided tape
  3. Ensure sensor faces forward when servo is at center position
  4. Mount servo to a stable base (breadboard, cardboard, etc.)

Make Connections

  1. Connect servo wires:
    • Red → 5V on Arduino
    • Brown/Black → GND on Arduino
    • Orange → Pin 6 on Arduino
  2. Connect ultrasonic sensor:
    • VCC → 5V on Arduino
    • GND → GND on Arduino
    • TRIG → Pin 9 on Arduino
    • ECHO → Pin 10 on Arduino
  3. Double-check all connections before powering on

Step 2: Install Software (10 minutes)

Download Processing

  1. Go to https://processing.org/download
  2. Download Processing for your operating system
  3. Install and open Processing

Prepare Arduino IDE

  1. Open Arduino IDE
  2. Select Tools → Board → "Arduino Mega or Mega 2560"
  3. Select Tools → Port → (your Arduino's COM port)

Step 3: Upload Arduino Code (5 minutes)

  1. Copy the Arduino code from the "Simple Arduino Radar Code" above
  2. Paste into Arduino IDE
  3. Click Upload (arrow button)
  4. Wait for "Done uploading" message

Test Arduino is Working

  1. Open Serial Monitor (Tools → Serial Monitor)
  2. Set baud rate to 9600
  3. You should see data like: 0,45 then 2,47 then 4,52 etc.
  4. Watch servo move from 0° to 180° and back

If this doesn't work, STOP HERE and let me know what's happening!


Step 4: Run Processing Display (5 minutes)

  1. Copy the Processing code from "Simple Processing Radar Display Code" above
  2. Open Processing and paste the code
  3. Click the Play button (triangle)

Fix Serial Port Connection

If you get an error about serial ports:

  1. Look at the console output in Processing
  2. Find your Arduino port in the list (usually COM3, COM4 on Windows)
  3. Change line 23 in the Processing code:

    myPort = new Serial(this, Serial.list()[0], 9600);
    

    Replace [0] with the correct number from the list

  4. Run again

Step 5: Enjoy Your Working Radar! 🎉

You should now see:

  • Green radar screen with distance circles and angle lines
  • Bright green sweep line rotating back and forth
  • Red dots appearing when objects are detected
  • Live information showing current angle and distance
  • "CONNECTED" status in green

Testing Your Radar

Test Object Detection

  1. Place objects at different distances in front of the sensor
  2. Watch red dots appear on the radar display
  3. Move objects around and see them tracked in real-time
  4. Try different sized objects - bigger objects show up better

Keyboard Controls

  • Press 'C' - Clear all detected objects from display
  • Press 'R' - Reconnect to Arduino if connection is lost

Troubleshooting Common Issues

Problem: Arduino Serial Monitor shows no data

Solutions:

  • Check servo and sensor power connections (5V and GND)
  • Verify TRIG → Pin 9, ECHO → Pin 10
  • Try different USB cable
  • Restart Arduino IDE

Problem: Processing can't connect to serial port

Solutions:

  • Close Arduino Serial Monitor first
  • Check which COM port Arduino is using (Tools → Port)
  • Change the [0] in Processing code to correct port number
  • Try running Processing as administrator

Problem: Servo doesn't move smoothly

Solutions:

  • Use external 9V power adapter for Arduino
  • Check servo power connections
  • Ensure servo isn't mechanically blocked

Problem: No objects detected

Solutions:

  • Test sensor with hand in front at different distances
  • Check TRIG and ECHO pin connections
  • Ensure sensor faces straight ahead
  • Try larger objects (books, boxes work well)

Customization Options

Adjust Scanning Speed

delay(100);  // Change to 50 for faster, 200 for slower

Change Angle Step Size

angle += direction * 2;  // Change 2 to 1 for smoother, 5 for faster

Modify Detection Range

if (distance > 2 && distance < 200) {  // Change 200 to desired max range

Change Radar Colors in Processing

stroke(0, 255, 0);     // Green - change to stroke(255, 0, 0) for red
fill(255, 0, 0);       // Red objects - change to fill(0, 0, 255) for blue

Why This Approach is Better for Learning

Immediate feedback - see exact distance readings
Easy debugging - watch data in real-time
Professional results - looks like real radar systems
Less complexity - fewer things to go wrong
Expandable - easy to add features later

This gives you a fully functional radar system that's perfect for demonstrations, learning, and impressing friends!


Next Steps (Advanced)

Once this works perfectly, you can:

  • Add sound effects when objects are detected
  • Log data to files for analysis
  • Add multiple sensors for wider coverage
  • Create a web interface to view remotely
  • Add object tracking to follow moving targets

But first, let's get the basic version working perfectly!

Comments4

Paul

3 months ago

#include <Servo.h>

// Create servo object
Servo radarServo;

// Define pins - ONLY 3 connections needed!
const int trigPin = 9;
const int echoPin = 10;
const int servoPin = 6;

// Variables
int angle = 0;
int direction = 1; // 1 for forward, -1 for backward

void setup() {
 // Initialize serial communication
 Serial.begin(9600);
 
 // Initialize pins
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 
 // Attach servo
 radarServo.attach(servoPin);
 
 // Move servo to starting position
 radarServo.write(0);
 delay(1000);
 
 Serial.println("Simple Radar Started");
}

void loop() {
 // Move servo to current angle
 radarServo.write(angle);
 delay(50); // Wait for servo to reach position
 
 // Measure distance
 int distance = measureDistance();
 
 // Send data to Processing in format: angle,distance
 Serial.print(angle);
 Serial.print(",");
 Serial.println(distance);
 
 // Update angle for next iteration
 angle += direction * 2; // Move 2 degrees at a time
 
 // Change direction when reaching limits
 if (angle >= 180) {
   direction = -1;
   angle = 180;
 } else if (angle <= 0) {
   direction = 1;
   angle = 0;
 }
 
 delay(100); // Delay between measurements
}

int measureDistance() {
 // Clear the trigPin
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 
 // Send 10 microsecond pulse
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin, LOW);
 
 // Read the echo pin
 long duration = pulseIn(echoPin, HIGH);
 
 // Calculate distance in cm
 int distance = duration * 0.034 / 2;
 
 // Limit maximum distance reading
 if (distance > 200 || distance < 2) {
   distance = 200; // Return max distance if no valid reading
 }
 
 return distance;
}

import processing.serial.*;

Serial myPort;
String data = "";
int angle = 0;
int distance = 0;

// Radar display settings
int centerX, centerY;
int maxRadius = 300;
ArrayList<PVector> objects;

void setup() {
 size(800, 600);
 
 // Set radar center
 centerX = width / 2;
 centerY = height - 80;
 
 // Initialize objects list
 objects = new ArrayList<PVector>();
 
 // List available serial ports
 println("Available serial ports:");
 for (int i = 0; i < Serial.list().length; i++) {
   println(i + ": " + Serial.list()[i]);
 }
 
 // Connect to Arduino - CHANGE [0] TO CORRECT PORT NUMBER
 try {
   myPort = new Serial(this, Serial.list()[0], 9600);
   myPort.bufferUntil('\n');
   println("Connected to: " + Serial.list()[0]);
 } catch (Exception e) {
   println("Could not connect to serial port!");
   println("Check your Arduino connection and change the port number in line 23");
 }
}

void draw() {
 // Dark background with fade effect
 fill(0, 30);
 rect(0, 0, width, height);
 
 // Draw radar grid
 drawRadarGrid();
 
 // Draw detected objects
 drawObjects();
 
 // Draw sweep line
 drawSweepLine();
 
 // Draw information
 drawInfo();
}

void drawRadarGrid() {
 stroke(0, 255, 0, 100);
 strokeWeight(1);
 noFill();
 
 // Draw distance circles
 for (int i = 1; i <= 4; i++) {
   float radius = (maxRadius / 4.0) * i;
   arc(centerX, centerY, radius * 2, radius * 2, PI, TWO_PI);
 }
 
 // Draw angle lines
 for (int a = 0; a <= 180; a += 30) {
   float radian = radians(a);
   float x = centerX + cos(radian) * maxRadius;
   float y = centerY - sin(radian) * maxRadius;
   line(centerX, centerY, x, y);
 }
 
 // Draw distance labels
 fill(0, 255, 0);
 textAlign(CENTER);
 textSize(12);
 for (int i = 1; i <= 4; i++) {
   int dist = (200 / 4) * i;
   float radius = (maxRadius / 4.0) * i;
   text(dist + "cm", centerX, centerY - radius + 5);
 }
 
 // Draw angle labels
 text("0°", centerX + maxRadius - 20, centerY + 20);
 text("90°", centerX, centerY - maxRadius + 20);
 text("180°", centerX - maxRadius + 20, centerY + 20);
}

void drawObjects() {
 fill(255, 0, 0);
 noStroke();
 
 // Draw all detected objects with fading
 for (int i = objects.size() - 1; i >= 0; i--) {
   PVector obj = objects.get(i);
   
   // Calculate position
   float radian = radians(obj.x);
   float dist = map(obj.y, 0, 200, 0, maxRadius);
   float x = centerX + cos(radian) * dist;
   float y = centerY - sin(radian) * dist;
   
   // Draw object with fading
   float alpha = map(i, 0, objects.size() - 1, 50, 255);
   fill(255, 0, 0, alpha);
   ellipse(x, y, 8, 8);
 }
 
 // Remove old objects (keep last 50)
 while (objects.size() > 50) {
   objects.remove(0);
 }
}

void drawSweepLine() {
 stroke(0, 255, 0);
 strokeWeight(2);
 
 float radian = radians(angle);
 float x = centerX + cos(radian) * maxRadius;
 float y = centerY - sin(radian) * maxRadius;
 
 line(centerX, centerY, x, y);
}

void drawInfo() {
 fill(0, 255, 0);
 textAlign(LEFT);
 textSize(16);
 
 text("ARDUINO RADAR SYSTEM", 20, 30);
 text("Angle: " + angle + "°", 20, 55);
 text("Distance: " + distance + " cm", 20, 80);
 text("Objects: " + objects.size(), 20, 105);
 
 if (myPort != null) {
   fill(0, 255, 0);
   text("● CONNECTED", 20, 130);
 } else {
   fill(255, 0, 0);
   text("● DISCONNECTED", 20, 130);
 }
 
 // Instructions
 textSize(12);
 text("Press 'c' to clear objects", 20, height - 40);
 text("Press 'r' to reconnect", 20, height - 25);
}

void serialEvent(Serial myPort) {
 try {
   data = myPort.readStringUntil('\n');
   
   if (data != null) {
     data = trim(data);
     
     // Parse angle and distance
     String[] values = split(data, ',');
     if (values.length == 2) {
       angle = int(values[0]);
       distance = int(values[1]);
       
       // Add object if valid distance
       if (distance > 2 && distance < 200) {
         objects.add(new PVector(angle, distance));
       }
       
       // Debug output
       println("Angle: " + angle + "°, Distance: " + distance + "cm");
     }
   }
 } catch (Exception e) {
   println("Error reading data: " + e.getMessage());
 }
}

void keyPressed() {
 if (key == 'c' || key == 'C') {
   objects.clear();
   println("Objects cleared");
 }
 
 if (key == 'r' || key == 'R') {
   // Reconnect to serial port
   if (myPort != null) {
     myPort.stop();
   }
   try {
     myPort = new Serial(this, Serial.list()[0], 9600);
     myPort.bufferUntil('\n');
     println("Reconnected");
   } catch (Exception e) {
     println("Reconnection failed");
   }
 }
}

Sketch uses 5682 bytes (2%) of program storage space. Maximum is 253952 bytes.
Global variables use 366 bytes (4%) of dynamic memory, leaving 7826 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't open device "\\.\COM5": The system cannot find the file specified.


avrdude: ser_drain(): read error: The handle is invalid.


avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.


avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.


avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.


avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.


avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.


avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.


avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
Failed uploading: uploading error: exit status 1

 

Paul

3 months ago

In reply to by Paul

🔧 Fix "Can't Open Device COM5" Error

Step 1: Find Your Arduino's REAL COM Port

  1. Unplug your Arduino from USB completely
  2. In Arduino IDE, go to Tools → Port
  3. Write down all COM ports you see (or take a screenshot)
  4. Plug your Arduino back in and wait 10 seconds
  5. Go to Tools → Port again
  6. Look for a NEW COM port that appeared - this is your Arduino!

Step 2: Windows Device Manager Check

  1. Press Windows Key + X
  2. Click "Device Manager"
  3. Look under "Ports (COM & LPT)"
  4. You should see "Arduino Mega 2560 (COMx)" or similar
  5. Note the COM number - this is your real port!

If you don't see Arduino in Device Manager:

🔴 Arduino Not Recognized - Driver Fix

Option A: Automatic Driver Install

  1. Unplug Arduino
  2. Download Arduino IDE again from arduino.cc
  3. Install fresh (this includes drivers)
  4. Plug Arduino back in

Option B: Manual Driver Install

  1. Go to Device Manager
  2. Look for "Unknown Device" or "USB Device"
  3. Right-click → Update Driver
  4. Browse to Arduino IDE folder → drivers
  5. Install the Arduino driver

🚀 Quick Solutions to Try Right Now

Solution 1: Try Different COM Ports

In Arduino IDE:

  • Tools → Port → COM3 (try uploading)
  • Tools → Port → COM4 (try uploading)
  • Tools → Port → COM6 (try uploading)
  • Keep trying until one works!

Solution 2: Reset Everything

  1. Close Arduino IDE completely
  2. Unplug Arduino
  3. Wait 30 seconds
  4. Plug Arduino back in
  5. Open Arduino IDE
  6. Check Tools → Port for available ports

Solution 3: Different USB Port/Cable

  • Try a different USB port on your computer
  • Try a different USB cable (some cables are power-only)
  • Avoid USB hubs - plug directly into computer

🔍 Diagnostic Questions

Tell me:

  1. What COM ports do you see in Tools → Port right now?
  2. Is there anything in Windows Device Manager under "Ports (COM & LPT)"?
  3. Does the Arduino LED light up when you plug it in?
  4. What computer are you using (Windows 10/11)?

💡 Most Likely Quick Fix

The real problem: You're trying to use COM5, but your Arduino is probably on COM3 or COM4.

Try this right now:

  1. Tools → Port
  2. Select COM3 (if available)
  3. Try uploading
  4. If that fails, try COM4, COM6, etc.

🎯 Emergency Solution - Use Different Computer

If nothing works:

  • Try a different computer (laptop, friend's computer)
  • This will tell us if it's a driver/software issue or hardware problem

Most of these COM port errors are fixed within 5 minutes once we find the correct port!

What COM ports do you see available in Tools → Port right now?