Arduino Radar Project

In this Arduino Tutorial I will show you how you can make this cool looking radar using the Arduino Board and the Processing Development Environment. You can watch the following video or read the written tutorial below for more details.

Overview

All you need for this Arduino Project is an Ultrasonic Sensor for detecting the objects, a small hobbyist Servo Motor for rotating the sensor and an Arduino Board for controlling them. You can watch the following video or read the written tutorial below.[/column]

Components needed for this Arduino Project

You can get these components from any of the sites below:

Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.

Building the device

  • First I made a cardboard stand for connecting the Ultrasonic sensor to the Servo motor. I folded it like it’s shown on the picture below, glued it and secured to the servo motor using a screw like this.
Arduino-Radar-Cardboard-Stand
  • Also I attached a pin header on which I soldered 4 jumper wires for connecting the sensor.
Arduino-Radar-Pin-Hearder
  • Finally I secured the servo motor to the Arduino Board using an elastic band.
Arduino-Radar-Complete

There are also some special mount bracket for the ultrasonic sensor from Banggod. You can get them from the following links:

  • Ultrasonic Sensor with Mounting Bracket ……… Amazon / AliExpress
  • Mounting Bracket For Ultrasonic Ranging …….. Banggood
ultrasonic-sensor-mount-brackets

Arduino Radar Circuit Schematics

I connected the Ultrasonic Sensor HC-SR04 to the pins number 10 and 11 and the servo motor to the pin number 12 on the Arduino Board.

Arduino-Radar-Circuit-Schematics

Source codes

Now we need to make a code and upload it to the Arduino Board that will enable the interaction between the Arduino and the Processing IDE.  For understanding how the connection works click here to visit my Arduino and Processing Tutorial.

Arduino-and-Processing-IDE

 Here’s the Arduino Source Code with description of each line of the code:

// Includes the Servo library
#include <Servo.h>. 

// Defines Tirg and Echo pins of the Ultrasonic Sensor
const int trigPin = 10;
const int echoPin = 11;
// Variables for the duration and the distance
long duration;
int distance;

Servo myServo; // Creates a servo object for controlling the servo motor

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600);
  myServo.attach(12); // Defines on which pin is the servo motor attached
}
void loop() {
  // rotates the servo motor from 15 to 165 degrees
  for(int i=15;i<=165;i++){  
  myServo.write(i);
  delay(30);
  distance = calculateDistance();// Calls a function for calculating the distance measured by the Ultrasonic sensor for each degree
  
  Serial.print(i); // Sends the current degree into the Serial Port
  Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
  Serial.print(distance); // Sends the distance value into the Serial Port
  Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
  }
  // Repeats the previous lines from 165 to 15 degrees
  for(int i=165;i>15;i--){  
  myServo.write(i);
  delay(30);
  distance = calculateDistance();
  Serial.print(i);
  Serial.print(",");
  Serial.print(distance);
  Serial.print(".");
  }
}
// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){ 
  
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH); 
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
  distance= duration*0.034/2;
  return distance;
}
Code language: Arduino (arduino)
Radar-Print-Screen-02

Now we will receive the values for the angle and the distance measured by the sensor from the Arduino Board into the Processing IDE using the SerialEvent() function which reads the data from the Serial Port and we will put the values of the angle and the distance into the variables iAngle and iDistance. These variable will be used for drawing the radar, the lines, the detected objects and some of the text.

For drawing the radar I made this function drawRadar() which consist of arc() and line() functions.

void drawRadar() {
  pushMatrix();
  translate(960,1000); // moves the starting coordinats to new location
  noFill();
  strokeWeight(2);
  stroke(98,245,31);
  // draws the arc lines
  arc(0,0,1800,1800,PI,TWO_PI);
  arc(0,0,1400,1400,PI,TWO_PI);
  arc(0,0,1000,1000,PI,TWO_PI);
  arc(0,0,600,600,PI,TWO_PI);
  // draws the angle lines
  line(-960,0,960,0);
  line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
  line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
  line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
  line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
  line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
  line(-960*cos(radians(30)),0,960,0);
  popMatrix();
}Code language: Arduino (arduino)

For drawing the line that is moving along the radar I made this function drawLine(). Its center of rotation is set with the translate() function and using the line() function in which the iAngle variable is used the line is redrawn for each degree.

void drawLine() {
  pushMatrix();
  strokeWeight(9);
  stroke(30,250,60);
  translate(960,1000); // moves the starting coordinats to new location
  line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // draws the line according to the angle
  popMatrix();
}Code language: Arduino (arduino)

For drawing the detected objects I made this drawObject() function. It gets the distance from ultrasonic sensor, transforms it into pixels and in combination with the angle of the sensor draws the object on the radar.

void drawObject() {
  pushMatrix();
  translate(960,1000); // moves the starting coordinats to new location
  strokeWeight(9);
  stroke(255,10,10); // red color
  pixsDistance = iDistance*22.5; // covers the distance from the sensor from cm to pixels
  // limiting the range to 40 cms
  if(iDistance<40){
    // draws the object according to the angle and the distance
  line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAngle)));
  }
  popMatrix();
}Code language: Arduino (arduino)

For the text on the screen I made the drawText() function which draws texts on particular locations.

All of these functions are called in the main draw() function which repeats all the time and draws the screen. Also here I am using this fill() function with 2 parameters for simulating motion blur and slow fade of the moving line.

void draw() {
  
  fill(98,245,31);
  textFont(orcFont);
  // simulating motion blur and slow fade of the moving line
  noStroke();
  fill(0,4); 
  rect(0, 0, width, 1010); 
  
  fill(98,245,31); // green color
  // calls the functions for drawing the radar
  drawRadar(); 
  drawLine();
  drawObject();
  drawText();
}Code language: Arduino (arduino)

Here’s the final appearance of the radar:

Arduino Radar Final Appearance

Here’s the complete Processing Source Code of the Arduino Radar:

import processing.serial.*; // imports library for serial communication
import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
import java.io.IOException;

Serial myPort; // defines Object Serial
// defubes variables
String angle="";
String distance="";
String data="";
String noObject;
float pixsDistance;
int iAngle, iDistance;
int index1=0;
int index2=0;
PFont orcFont;

void setup() {
  
 size (1920, 1080);
 smooth();
 myPort = new Serial(this,"COM4", 9600); // starts the serial communication
 myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
 orcFont = loadFont("OCRAExtended-30.vlw");
}

void draw() {
  
  fill(98,245,31);
  textFont(orcFont);
  // simulating motion blur and slow fade of the moving line
  noStroke();
  fill(0,4); 
  rect(0, 0, width, 1010); 
  
  fill(98,245,31); // green color
  // calls the functions for drawing the radar
  drawRadar(); 
  drawLine();
  drawObject();
  drawText();
}

void serialEvent (Serial myPort) { // starts reading data from the Serial Port
  // reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
  data = myPort.readStringUntil('.');
  data = data.substring(0,data.length()-1);
  
  index1 = data.indexOf(","); // find the character ',' and puts it into the variable "index1"
  angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle the Arduino Board sent into the Serial Port
  distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of the distance
  
  // converts the String variables into Integer
  iAngle = int(angle);
  iDistance = int(distance);
}

void drawRadar() {
  pushMatrix();
  translate(960,1000); // moves the starting coordinats to new location
  noFill();
  strokeWeight(2);
  stroke(98,245,31);
  // draws the arc lines
  arc(0,0,1800,1800,PI,TWO_PI);
  arc(0,0,1400,1400,PI,TWO_PI);
  arc(0,0,1000,1000,PI,TWO_PI);
  arc(0,0,600,600,PI,TWO_PI);
  // draws the angle lines
  line(-960,0,960,0);
  line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
  line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
  line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
  line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
  line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
  line(-960*cos(radians(30)),0,960,0);
  popMatrix();
}

void drawObject() {
  pushMatrix();
  translate(960,1000); // moves the starting coordinats to new location
  strokeWeight(9);
  stroke(255,10,10); // red color
  pixsDistance = iDistance*22.5; // covers the distance from the sensor from cm to pixels
  // limiting the range to 40 cms
  if(iDistance<40){
    // draws the object according to the angle and the distance
  line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAngle)));
  }
  popMatrix();
}

void drawLine() {
  pushMatrix();
  strokeWeight(9);
  stroke(30,250,60);
  translate(960,1000); // moves the starting coordinats to new location
  line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // draws the line according to the angle
  popMatrix();
}

void drawText() { // draws the texts on the screen
  
  pushMatrix();
  if(iDistance>40) {
  noObject = "Out of Range";
  }
  else {
  noObject = "In Range";
  }
  fill(0,0,0);
  noStroke();
  rect(0, 1010, width, 1080);
  fill(98,245,31);
  textSize(25);
  text("10cm",1180,990);
  text("20cm",1380,990);
  text("30cm",1580,990);
  text("40cm",1780,990);
  textSize(40);
  text("Object: " + noObject, 240, 1050);
  text("Angle: " + iAngle +" °", 1050, 1050);
  text("Distance: ", 1380, 1050);
  if(iDistance<40) {
  text("        " + iDistance +" cm", 1400, 1050);
  }
  textSize(25);
  fill(98,245,60);
  translate(961+960*cos(radians(30)),982-960*sin(radians(30)));
  rotate(-radians(-60));
  text("30°",0,0);
  resetMatrix();
  translate(954+960*cos(radians(60)),984-960*sin(radians(60)));
  rotate(-radians(-30));
  text("60°",0,0);
  resetMatrix();
  translate(945+960*cos(radians(90)),990-960*sin(radians(90)));
  rotate(radians(0));
  text("90°",0,0);
  resetMatrix();
  translate(935+960*cos(radians(120)),1003-960*sin(radians(120)));
  rotate(radians(-30));
  text("120°",0,0);
  resetMatrix();
  translate(940+960*cos(radians(150)),1018-960*sin(radians(150)));
  rotate(radians(-60));
  text("150°",0,0);
  popMatrix(); 
}
Code language: Arduino (arduino)

New Updated version of the Arduino Radar code to fit any screen resolution:

Just change the values in size() function, with your screen resolution.

/*   Arduino Radar Project
 *
 *   Updated version. Fits any screen resolution!
 *   Just change the values in the size() function,
 *   with your screen resolution.
 *      
 *  by Dejan Nedelkovski, 
 *  www.HowToMechatronics.com
 *  
 */

import processing.serial.*; // imports library for serial communication
import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
import java.io.IOException;

Serial myPort; // defines Object Serial
// defubes variables
String angle="";
String distance="";
String data="";
String noObject;
float pixsDistance;
int iAngle, iDistance;
int index1=0;
int index2=0;
PFont orcFont;

void setup() {
  
 size (1920, 1080); // ***CHANGE THIS TO YOUR SCREEN RESOLUTION***
 smooth();
 myPort = new Serial(this,"COM4", 9600); // starts the serial communication
 myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
 orcFont = loadFont("OCRAExtended-30.vlw");
}

void draw() {
  
  fill(98,245,31);
  textFont(orcFont);
  // simulating motion blur and slow fade of the moving line
  noStroke();
  fill(0,4); 
  rect(0, 0, width, height-height*0.065); 
  
  fill(98,245,31); // green color
  // calls the functions for drawing the radar
  drawRadar(); 
  drawLine();
  drawObject();
  drawText();
}

void serialEvent (Serial myPort) { // starts reading data from the Serial Port
  // reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
  data = myPort.readStringUntil('.');
  data = data.substring(0,data.length()-1);
  
  index1 = data.indexOf(","); // find the character ',' and puts it into the variable "index1"
  angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle the Arduino Board sent into the Serial Port
  distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of the distance
  
  // converts the String variables into Integer
  iAngle = int(angle);
  iDistance = int(distance);
}

void drawRadar() {
  pushMatrix();
  translate(width/2,height-height*0.074); // moves the starting coordinats to new location
  noFill();
  strokeWeight(2);
  stroke(98,245,31);
  // draws the arc lines
  arc(0,0,(width-width*0.0625),(width-width*0.0625),PI,TWO_PI);
  arc(0,0,(width-width*0.27),(width-width*0.27),PI,TWO_PI);
  arc(0,0,(width-width*0.479),(width-width*0.479),PI,TWO_PI);
  arc(0,0,(width-width*0.687),(width-width*0.687),PI,TWO_PI);
  // draws the angle lines
  line(-width/2,0,width/2,0);
  line(0,0,(-width/2)*cos(radians(30)),(-width/2)*sin(radians(30)));
  line(0,0,(-width/2)*cos(radians(60)),(-width/2)*sin(radians(60)));
  line(0,0,(-width/2)*cos(radians(90)),(-width/2)*sin(radians(90)));
  line(0,0,(-width/2)*cos(radians(120)),(-width/2)*sin(radians(120)));
  line(0,0,(-width/2)*cos(radians(150)),(-width/2)*sin(radians(150)));
  line((-width/2)*cos(radians(30)),0,width/2,0);
  popMatrix();
}

void drawObject() {
  pushMatrix();
  translate(width/2,height-height*0.074); // moves the starting coordinats to new location
  strokeWeight(9);
  stroke(255,10,10); // red color
  pixsDistance = iDistance*((height-height*0.1666)*0.025); // covers the distance from the sensor from cm to pixels
  // limiting the range to 40 cms
  if(iDistance<40){
    // draws the object according to the angle and the distance
  line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),(width-width*0.505)*cos(radians(iAngle)),-(width-width*0.505)*sin(radians(iAngle)));
  }
  popMatrix();
}

void drawLine() {
  pushMatrix();
  strokeWeight(9);
  stroke(30,250,60);
  translate(width/2,height-height*0.074); // moves the starting coordinats to new location
  line(0,0,(height-height*0.12)*cos(radians(iAngle)),-(height-height*0.12)*sin(radians(iAngle))); // draws the line according to the angle
  popMatrix();
}

void drawText() { // draws the texts on the screen
  
  pushMatrix();
  if(iDistance>40) {
  noObject = "Out of Range";
  }
  else {
  noObject = "In Range";
  }
  fill(0,0,0);
  noStroke();
  rect(0, height-height*0.0648, width, height);
  fill(98,245,31);
  textSize(25);
  
  text("10cm",width-width*0.3854,height-height*0.0833);
  text("20cm",width-width*0.281,height-height*0.0833);
  text("30cm",width-width*0.177,height-height*0.0833);
  text("40cm",width-width*0.0729,height-height*0.0833);
  textSize(40);
  text("Object: " + noObject, width-width*0.875, height-height*0.0277);
  text("Angle: " + iAngle +" °", width-width*0.48, height-height*0.0277);
  text("Distance: ", width-width*0.26, height-height*0.0277);
  if(iDistance<40) {
  text("        " + iDistance +" cm", width-width*0.225, height-height*0.0277);
  }
  textSize(25);
  fill(98,245,60);
  translate((width-width*0.4994)+width/2*cos(radians(30)),(height-height*0.0907)-width/2*sin(radians(30)));
  rotate(-radians(-60));
  text("30°",0,0);
  resetMatrix();
  translate((width-width*0.503)+width/2*cos(radians(60)),(height-height*0.0888)-width/2*sin(radians(60)));
  rotate(-radians(-30));
  text("60°",0,0);
  resetMatrix();
  translate((width-width*0.507)+width/2*cos(radians(90)),(height-height*0.0833)-width/2*sin(radians(90)));
  rotate(radians(0));
  text("90°",0,0);
  resetMatrix();
  translate(width-width*0.513+width/2*cos(radians(120)),(height-height*0.07129)-width/2*sin(radians(120)));
  rotate(radians(-30));
  text("120°",0,0);
  resetMatrix();
  translate((width-width*0.5104)+width/2*cos(radians(150)),(height-height*0.0574)-width/2*sin(radians(150)));
  rotate(radians(-60));
  text("150°",0,0);
  popMatrix(); 
}Code language: Arduino (arduino)

356 thoughts on “Arduino Radar Project”

  1. Thanks for setting up a nice project. I was able to follow and my project works. The only issues i found that the scanning is not very fast. I tired to reduce the angle and at the end looked into increasing the serial baud rate which didn’t resulted in fast scanning. Serial monitor always showed very same reading speed. So, the radar lines on frame move very slowly and distance get updated slow when compared to you video.

    Reply
  2. hi, i want to construct it for my school project. but i just have a week for that. can it be made that easily? in addition to that i have zero knowledge of arduino devices. should i just follow the steps? or is there any more explanation on your site? being honest i m really confused

    Reply
    • Hi there, well if you follow all the steps from the video and the article the project should work. There isn’t anything hidden, though you would need a bit of knowledge in case you connect something wrong, because you will wonder that is going on. Check my other beginner tutorials if you are complete beginner.

      Reply
  3. I realize I’m just another voice in the choir, here, but I feel I have to say it anyway: This was a delightfully whimsical project. I did “just because”, and it was very fun. Thanks! I learned a handful of things that may turn out ot be useful, later on.

    Reply
  4. Really cool tutorial!
    I was just wondering if there was a way to use that GUI on the 3.1″ TFT Screen you also made a tutorial of?

    Reply
    • Thanks! Of course, everything is possible with Arduino, but that would requite appropriate code changes. You would have to code the GUI to suit the TFT screen.

      Reply
  5. Really cool project! And, it was easy enough for me to pull off with only minimal mess ups. I only first bought an Arduino (Uno R3+) 3 days ago. I went through all of the tutorials in the starter kit I bought, and then purchased some other stuff to add on to it (shields, sensors, etc.).

    I really appreciate the tutorial on setting up and working with Processing, as well. I didn’t know about that before, but now can add that into my learning. Thanks!

    Reply
      • Yes sorry I found that. But also in the latest ‘complete source code’ bit, there is no #include and I am getting confused and I have already written half of the the code titled in red letters. Help!

        Reply
  6. Great site, great project and thanks for making everyting fun and easy.

    I just wanted to ask that, is it possible to adapt the code for measuring the speed of an approaching object. I reduced the angle of scanning to 60 degrees and I want to see the speed on the screen if an object is getting closer to the sensor. Any tips to get me started?

    Thanks in advance.

    Reply
  7. Dejan, The project is excellent. The code all works and the instructions and tutorials are excellent. My only trouble was finding out how to clear the font error in Processing but a quick google search taught me how to create the font. It’s a great project!

    Reply
  8. hi i just want to ask how can i match the distance of the detected object in the sonar since i already change the distance that the sensor to 1m, the distance that the sonar give doesnt match with the distance that the sensor detect

    Reply
  9. Hi Dejan,
    I get the program to work some of the time, but not every time. The sensor will often hesitate on the swing back (165 to 15 degrees) at about 80 to 90 degrees and then will often hesitate on the swing forward (15 to 165 degrees) at about 70-80 degrees. Any idea why it hesitates on the swing back and forward? What is weird, is that sometimes it doesn’t hesitate at all, but most of the time it does. Any help would be appreciated.

    Reply
  10. Thanks a ton man!. The project definitely works. The coding is free of error. There is just one slight modification though. The font which you use in the processing IDE needs to be moved into the sketch folder first and you seem to have skipped mentioning that part.
    Other than that, this one is an awesome project indeed.
    Cheers

    Reply
  11. I Dejan,
    Just finished building your Radar Program. Works Great! Loved making it. Only problems with font and ports. Thanks for sharing it with us.

    Reply
  12. Hello there!

    can you explain the formula used for the distance

    distance= duration*0.034/2;

    how you got to it, if you may please?

    Reply
  13. Hello and thank you for this project, its really nice

    I have a problem but beside this all is good
    The problem is the servo motor is not rotating smoothly I always have to push it and force it to rotate it does not rotate on itself
    Can you help me?

    Reply
  14. The ultrasonic sensor u used for this project is HC- SR04. I read data sheet of it. range of sensor is upto 400 cm. then why only upto 40 cm can be got by this code. if we consider its measuring efficiency is lesser than ideal one then also it could measure atleast upto 100cm. What changes in code required if i want output of 400cm or 100cm.

    Reply
  15. I need the most high possible precision for my project but this code (processing code) is not very precise. Arduino and the sonar are working good, sending the right distance to the serial port. Processing IDE is recieving the right distance but the results showed by the radar are not! The value showed near “Distance” is correct but the red line is wrong by 3, sometimes 4 cm. Also, the segment from point 0 and 10 cm is much bigger then segments between 10-20, 20-30 and 30-40. I also modified the processing code to show red lines only at a certain distance (eg. 10cm) to see exactly how much is the red line long when processing read 10cm from the serial port and the red line is at about 7/8cm (so it starts before the 10cm segment). Same as for 20cm or any other distance.

    Reply
    • That’s true, this project is not that accurate, considering both the cheap electronics components used in this project, as well as the coding in the Processing IDE. The point was to make it as simple as possible so that everyone can easily understand it and make it on their own, and sure there is always room for any project to be improved.

      Reply
  16. Can i make the radar screen with LCD touch screen 2.8 or 3.2 inch? And if the answer is yes, can you give the code with LCD screen (processing code). thanks very much bro!

    Reply
  17. It Works!! Just replaced “30” to “48” (in orcfont line) in latest processing IDE(3.2.3) and adjusted the screen size.

    Reply
  18. hey, i really like this project you have, but I am having, is that for starters the screen for some reason does not fit, but my main problem is that the red lines are not showing up for me when i run the program. everything else is working fine, the green lines are moving and all, but when i place somthing in front of the sensor, no red lines appear. do you know how to fix this? thanks for the help

    Reply
  19. Hi Dejan!! Can You Tell Me How Can I Make A Similar Radar Like You Using A Stepper Motor Instead Of Using Servo Motor???

    Reply
      • Is This Arduino Code Is Correct Or Not For THis Radar By Using Stepper Motor:-

        // Including Required Libraries
        #include // Library For Stepper
        #include // Library For SONAR

        AF_Stepper Radar(200, 2); // Stepper Configuration For Port Number And Steps/Revolution

        #define PING_PIN 12 // Arduino Pin 12 Connected To Ping pin Of HC-SR04

        NewPing sonar(PING_PIN, PING_PIN); //Sensor Configuration

        unsigned int distance1; // Variable For Storing Sensed Distance
        unsigned int distance2;

        void setup()
        {
        Serial.begin(9600); // Initializing Seial COmmunication At 9600bps
        Radar.setSpeed(20); // Configuring Stepper RPM
        }

        void loop()
        {
        for(int i = 0; i = 0; i–)
        {
        Radar.step(1, BACKWARD, SINGLE);
        delay(5);
        distance2 = sonar.ping() / US_ROUNDTRIP_CM;
        delay(5);
        Serial.print(i*1.8);
        Serial.print(“,”);
        Serial.print(distance2);
        Serial.print(“.”);
        }

        Reply
  20. Thank you man this is a great job!!
    It works perfect I only have to change 2 things to make it work on ubuntu, this is one of them:

    I change this:
    myPort = new Serial(this,”COM4″, 9600);

    to my ubuntu serial:
    myPort = new Serial(this,”/dev/ttyUSB0″, 9600);

    And the font too:
    myFont = createFont(“Georgia”, 32);

    But wen I change the SCREEN RESOLUTION the draw of the void drawRadar is more small than the lines.

    how can I fix the screen resolution to match with? size (1100, 880);

    thank you for this great tutorial I really appreciate it!

    Reply
    • Are you using the right Processing IDE code, the updated to work on each screen resolution, the one on the bottom of the post. If you are using that one you just have to set your screen resolution and all other drawings will be adjusted according to the set resolution.

      Reply
  21. Hello sir!
    I’m having a small problem. The green and red lines are not moving at all and the angle is only showing 0° all the time. Please give me some instructions of solving this problem!

    Thank’s for a cool Project!

    Reply
  22. Hi sir, thank you for your great tutorial ! but I have a problem. It says in the Processing IDE that “Could not load font OCRAExtended-30.vlw. Make sure that the font has been copied to the data folder of your sketch.”. Can you help me out sir , please ?

    Reply
  23. Hi Dejan,
    Great project. Even I have followed and done it. Everything is working fine but the problem I am facing is that my servo motor is getting hot and after 1 or 2 rotation it stops rotating and then it doesn’t rotate till it doesn’t cool down. May be next day it start to work and again after 2 roation it heats up and stops.

    I want to just ask you that whatever distance which is measured, I want it to be uploaded to my Cloud, So can I do that? Can you help me out? Please.!

    Reply
    • Hi,
      Well you might have a faulty servo motor.
      Sure you could store your measurements, but I don’t have any tutorial about storing them on Cloud. If storing them to a MicroSD card could do the job for you, you can check my particular tutorial for that.

      Reply
  24. Hi,
    Really helpful tutorial.
    I am experiencing really noisy HC-SR04 data. I was wondering if you have experienced that and if so how did you solve it. Or do you have any advice on what might be the problem.

    Reply
  25. Hi, one basic doubt I’m facing, pardon me if i’m being a stupid here.

    How’s the angle measured from the data ? Considering ultrasonic sensor returns only the distance to an object.

    Reply
  26. Hey, great project!!! 🙂
    But I wanted to know how can we make it rotate 360 degrees because the servo can rotate up to 190 degrees. Can we have a wireless radar configuration for making it rotate 360 degrees or a sensor equivalent to 360 radiation pattern?
    pls help me out!!!
    Thank u

    Reply
  27. Hi Dejan I would like to know how did you set up the screen and how to connect it in order to have the green radar lines going on if you could explain me this thank you I already scrolled the other comments…

    Jonny

    Reply
  28. Great project! However I did have a problem downloading the processing sketch for the screen. Do you know why? Thanks.

    Reply
  29. Hi again,

    The resolution issue is solved. I think I had used a previous version of your code, I see that all graphics are sized for width and height of the size() function.

    Thanks!

    Reply
  30. Hi Dejan,

    Thanks for making this project available, it’s very impressive. We brought it to a group of about 60 students and they made it. All were very impressed with the results.
    I’ve done it on my computer and it works very well. On the student laptops, coming with many different setups, screen resolutions and operating systems, we had issues on some. The main one was with resolution. Even using your last code for all screen resolution, and changing the “size (1920, 1080); ” line with their respective screen resolution did not change the size of the radar graph. We can only see the top left corner of the radar, with the base and angles-distances out of the screen. This mainly happened with the lower screen resolutions, around 1360, 768. I think other feedbacks mentioned this as well, I’m trying to troubleshoot on my computer but if you can help it would be great.
    Others were getting error messages when compiling the Arduino code, I’m thinking it could be linked to their antivirus softwares as they were getting prompts from it. Anyway we’ll work through this one.

    Thanks again for sharing this code, it made the kids very happy!

    Reply
  31. Hello Sir,

    I have a problem with Processing. Last time I used this app everything functioned. Now the radar’s drawing is broke. I can’t attach a picture to show you what is happening. Radar appear regular when I open Processing but it doesn’t scan the near environment. It just draw a bold red line from the center to the begining degree of scanning.

    Reply
  32. Hi, My daughter is about to do this project with her weekend Science group (all 12 years old).
    I just wanted to say that the code and the video and the explanations are excellent, and I think this will be an excellent project for them.

    I am also going to use it to introduce the concept of Radians to them, as a side note.
    Many thanks for your all your efforts and explanations and tutorials. A truly inspirational site.

    Reply
  33. Hello dejan,
    Thank you for the great project!!!
    I have a question regarding the display. after clicking the run button in processing, my display only shows partial screen of the scanning radar. Changing the display resolution does not fix the problem. I also change to different font. Please help.
    Thanks in advance.

    Reply
  34. Hello Sir, for the updated display code I am getting an error which reads:

    exit status 1
    ‘import’ does not name a type

    This error is for this code “import java.io.IOException;”

    Reply
  35. Dear Dejan
    thank you so much for your great projet ,so to make it works i’ve changed :
    “COM4” to “COM12” in Pocessing code.
    “OCRAExtended-30.vlw” to “OCRAExtended-48.vlw” wich already exist in my computer.
    and since i’m not familier with IDE Processing i still trying to change the resolution wich comes for (1920, 1080) screen i guess ,in way to make it compatible with my own 1280*1024.
    if could help me that’s gonna be great .
    thank you

    Reply
  36. I tried to use this code but it seems that the bottom half is in Javascript instead of c++ or any other compatible code, so it won’t work with my Arduino. How could I fix this?

    Reply
  37. Hello Sir,
    How can I use this code to drive my robot for the nearest object ?
    I have the nearest object angel and distance, but I don’t know how to control the motors for this position

    Reply
  38. we have used your code word to word and even worked out the font and screen resolution errors. But in the end we are facing a problem. when we disconnect the sensor, the green line shows but as soon as we connect the sensor the green lines disappear and only the red lines are visible. The sensor doesn’t detect anything as the distance is always 0 but the red lines move from 15-165 degrees. we thought there was something wrong with the sensor so we changed it but that didn’t help. so please help.

    Reply
  39. hello sir, when i am uploading my arudino uno code into arduino software program is uploaded but my servo motor is not rotated why sir.

    Reply
  40. How to make your processing code to draw more range than 40?I cant make it correctly(It will be nice to show ,how to make it to show 60cm and more)

    Reply
  41. sir i m not getting any output on screen of ide processing it does not show anything
    can you please tell do i need anyother java software install in pc???
    java.lang.NullPointerException i got this error

    Reply
  42. Can the given processing code work on Processing 3.0.2…….for some unknown reason i am not getting any output after i run the code because or is there any additional steps i need to take before/after uploading the arduino code and then immediately running the processing code

    Reply
  43. Hello….
    My console window in processing is not showing…no matter how many times i press run…what should i do?

    Reply
    • I have copied the 2 programs for arduino and processing as given…..but after connecting the arduino uno to my laptop and running the code in processing the console window is not appearing…….the program is uploaded in the arduino and the connections are fine….i am getting the output on the serial monitor…….i am a beginner so i am not sure where i am going wrong..

      Reply
  44. import processing.serial.*; // imports library for serial communication
    import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
    import java.io.IOException;
    HER ARDUINO SHOWS AN ERROR MESSAGE ‘import’ does not name a type

    Reply
  45. Hello Sir, it has been a great fun doing this project.
    But can you please tell me how can I increase the range of the radar more than 40 cms.
    The range of the project given here is 40 cms.
    Kindly .

    Reply
  46. Hello sir,
    While i’m trying to run the processing code the processing window get hanged and these errors are shown.
    Could not run the sketch (Target VM failed to initialize).
    For more information, read revisions.txt and Help ? Troubleshooting.
    Can you help me to solve the error.

    Reply
  47. pushMetrix() and popMetrix() was not declared in this program.
    Make sure these function whether should be declare or not.

    Reply
  48. Hello sir…!!
    i want to try your project but i have a question that can i use two ultrasonic sensors instead of one to make my Radar at 360 degree?

    Reply
      • thanks for your reply sir, can you please guide me a little bit about the modifications.?
        i’ll be very grateful to you.

        Reply
      • void drawObject() {
        pushMatrix();
        translate(960,1000); // moves the starting coordinats to new location
        strokeWeight(9);
        stroke(255,10,10); // red color
        pixsDistance = iDistance*22.5; // covers the distance from the sensor from cm to pixels
        // limiting the range to 40 cms
        if(iDistance<40){
        // draws the object according to the angle and the distance
        line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAngle)));
        }
        popMatrix();
        }
        i've copied all the code before proccesing into the arduino ide and it gives the below error while verifying the code.
        error= ''pushMatrix is not declared in this scope''
        please help.

        Reply
    • Read the other comments of this tutorial and you will see that the most of the people have managed to get it working. So the program is working, the problem has to be with you, you are probably doing something wrong.

      Reply
  49. Greetings sir.
    I have copied and pasted the code of Processing IDE as said before, but i am unable to get any of the background that was shown before each code.
    For sample, I had tried the program you have given to generate arcs(the first processing IDE program).
    But I am not getting any display when I hit play.
    Is it necessary for the arduino to be connected to get the display in the processing IDE?

    Reply
  50. hi sir good day thank for the amazing project I like it . but im not experience , I want to ask u about 1 thing i upload the arduino code its good done uploading but at the prociccing i get the error :

    COULD not load Font OCRAExtened-30.vlw. Make sure that the font has been copied to the data folder of your sketch

    Reply
  51. Hi Dejan, first I have to say that I saw your other projects and I am glad to see that we also have succesful arduino developers in our neighborhood. 😀 . Now I have to ask you something: I need to change measuring distance to use max range of 6m.What part of .pde code I need to modify ( I know I have to modify pixsDistance but dont know how). I was hoping that you could help me.
    Wish you good luck with your projects 😀

    Reply
    • Thanks!
      Here’s the point with the range:
      “pixsDistance = iDistance*((height-height*0.1666)*0.025); // covers the distance from the sensor from cm to pixels”
      This line corresponds to 40cm range. “iDistance” is distance from the sensor in cm and “(height-height*0.1666)” is the size of the radar in pixels depending on your screen resolution and these two things require no change. What you need to change is the “0.025” coefficient according to your desire range.
      Let’s say you want 2 meters range which is 5 times bigger then 40cm, so in that case the coefficient would be 0.025 / 5 = 0.05.
      Let me know if this worked for you.

      Reply
  52. Nice guide! Made one myself and it works perfectly. In Linux, however, you get nullpointexceptions regularly from the tyyACM port. This isn’t a problem as long as you throw the exception away and let it continue, which in your current version it does not. Simplest fix is to surround your serialEvent() function with a trycatch 🙂 should make it skip less in windows as well.

    Reply
  53. Can some one please mention a download link for the above libraries for this project. Thank you. Libraries are not available.

    Reply
      • Processing IDE is not working. I think there might be a problem with the screen resolution. I amended the resolution, but still processing is not working. No problem with the Arduino code. Problem arises with the processing code. Can you please clarify.

        Thank you

        Reply
  54. Hello Sir!
    We have followed your video for a test in school and we enjoyed it very much. But when we try it ourselves we can get all the programs working and the code into the arduino Mega, but the servo motor turns very slowly and the sensor is not working like it should. The Processing screen is just showing red all the time but is going in the same speed as the servo. Do you have any advice?
    Thank you for answers!

    Reply
    • Make sure your servo motors works properly using different codes just for the servo, as well as make sure your Ultrasonic sensor works properly (you can check that through the codes of my tutorials for the particular topic). As for the servo motor you can also try to change the speed of rotation by changing the delay time in the Arduino code in the for loop for the servo. As for the Processing IDE part, make sure you use the last (latest) updated version of the code which is at the bottom of the post.

      Reply
  55. sir…
    where code for change the distance?
    i search but didnt find.. can you help me show where code i must change?
    i need you advice
    Thanks for your attention

    Reply
  56. And i tried to change the pin to 8 9 and 10 in my uno but the program was same then it should create the error but though no error and no movement. please help solving my problem.

    Reply
  57. Is their any changes required in Ardunio Uno ? or the same procedure we need to follow, any pin changes or program changes ?

    Thank you in advance ..

    Reply
      • Hey Dejan sir, nice project i was so excited to do and i started doing it but once i compiled code in both ardunio and proc it don’t gave error, but my servo doesn’t move once ardunio is compiled and once if i compile proc then it opens the Graph and that too moving can u fix it out.

        Thank You for wonderful share.

        Reply
  58. hello Sir…
    can you share how to change the radar distance, i want to change 1 meter…
    in your project use 40cm.
    thank you sir..

    Reply
  59. Hi Dejan. While Uploading the Processor to the board I got this error “Could not load font OCRAExtended-30.vlw. Make sure that the font has been copied to the data folder of your sketch ” What does it mean sir thank you.

    Reply
  60. Hi, I’am MJ.
    Yesterday while I was building the radar, ofcurse I was a bit confused in the coding part. I think that u meant to copy the arduino code and put on the arduino coding place and upload it on the board, and then copy and paste the processing code and do the same. But I have a small issue. When I want to upload the code of the processing I get this error about the “myPort = new Serial(this,”COM4″, 9600);” on this place i get problems. It says: Error Opening serial port COM4: Port not found?
    Dejan please help me out I really need to finish this project in a matter of a week!! THANK YOU FOR YOUR ATTENTION SIR

    Reply
  61. i want a ultrasonic sensor covering a range of 10mts or above 10meters so please give the details of the sensor what i have to use in order to cover 10mts range and as well as the layout of the connections we we have to build on arduino board awating for your reply and thankful for seeing

    Reply
    • It can be done, but sorry I cannot do custom codes. This tutorial and all my other tutorials are here to help you learn about Arduino and some coding, so you are able to achieve the level needed to make your own code for your own project.

      Reply
    • Hi mate !
      You have to add a piezo to your circuit
      select a pin of your choise to connecti it
      then add these lines to your code

      const int piezoPin = 8;

      int notes[] = {262, 462, 862, 1662, 3262}; // Enter here the notes you like

      and call this function whenever you want to make noise your piezo

      void beep(){
      if(distance > 40){
      noTone(piezoPin);
      delay(10);
      noTone(piezoPin);
      delay(30);
      }
      else if (distance 30){
      tone(piezoPin, notes[1]);
      delay(10);
      noTone(piezoPin);
      delay(30);
      }
      else if (distance 20){
      tone(piezoPin,notes[2]);
      delay(10);
      noTone(piezoPin);
      delay(30);
      }
      else if (distance 10){
      tone(piezoPin,notes[3]);
      delay(10);
      noTone(piezoPin);
      delay(30);
      }
      else {
      tone(piezoPin,notes[4]);
      delay(10);
      noTone(piezoPin);
      delay(30);
      }
      }
      i hope this will help you

      Reply
  62. Please can u help me I got this problem “Error opening serial portCOM4:port not found” when I try to copilet, do u know the problem???

    Reply
      • I tried some things, but I when I tried to upload the first code, I got the following error:

        Arduino: 1.6.6 (Mac OS X), Board: “Arduino/Genuino Uno”

        /Users/Username/Schoolwerk/HKU/If This then That/Prototype 1/code1/code1.ino:2:19: warning: extra tokens at end of #include directive [enabled by default]
        #include .
        ^

        Sketch uses 5,136 bytes (15%) of program storage space. Maximum is 32,256 bytes.
        Global variables use 237 bytes (11%) of dynamic memory, leaving 1,811 bytes for local variables. Maximum is 2,048 bytes.
        avrdude: ser_open(): can’t open device “COM1”: No such file or directory
        ioctl(“TIOCMGET”): Inappropriate ioctl for device

        Reply
    • Never mind the other comment, I figured it out and everything works fine now! Thank you for putting up this wonderful tutorial!

      Reply
  63. sorry can you tell me how can I do a code to turn on a led with this same example but turn on the led to any distance you want to???
    CAN YOU HELP ME PLEASE????

    Reply
  64. Dear sir,

    My sensor is showing “0” distance in any way.
    And the radar is showing red due to the zero reading
    can you please find the problem

    Reply
  65. Sir,i am new in the ground of arduino and after surveying many videos and website i decided to choose yours project though i was feeling satisfied and was very exited of making myself one and i did it bt the issue i am facing is everything works great only the radar which is appearing in the screen is not moving and functioning please sir help me

    Reply
    • Give me some more details about your problem. It can be anything. Did you upload the Arduino sketch to Arduino properly, check if it’s working properly with the Serial Monitor. Also, did you use the updated version of the Processing IDE code which is at the bottom of the post.

      Reply
      • thank u sir for your concern it really helped me as u said to check i just again started from the very begnning and used the new processing sketch and now it is working thank you sir

        Reply
    • This happened to me too. But when I ran the processing code a several times it started to work properly. It might be the software freezing.

      Reply
  66. good day. here some errors what to do ?
    sketch_jan10b:12: error: ‘import’ does not name a type

    import java.awt.event.KeyEvent; // imports library for reading the data from the serial port

    ^

    sketch_jan10b:13: error: ‘import’ does not name a type

    import java.io.IOException;

    ^

    sketch_jan10b:14: error: ‘Serial’ does not name a type

    Serial myPort; // defines Object Serial

    ^

    sketch_jan10b:24: error: ‘PFont’ does not name a type

    PFont orcFont;

    Reply
  67. i’m getting the following message after running the arduino code:

    C:\Users\User\Documents\Arduino\libraries\sketch_jan09a\sketch_jan09a.ino:2:19: warning: extra tokens at end of #include directive [enabled by default]

    #include .

    ^

    Sketch uses 6,138 bytes (2%) of program storage space. Maximum is 253,952 bytes.
    Global variables use 348 bytes (4%) of dynamic memory, leaving 7,844 bytes for local variables. Maximum is 8,192 bytes.
    Invalid library found in C:\Users\User\Documents\Arduino\libraries\sketch_jan09a: C:\Users\User\Documents\Arduino\libraries\sketch_jan09a
    Invalid library found in C:\Users\User\Documents\Arduino\libraries\sketch_jan09a: C:\Users\User\Documents\Arduino\libraries\sketch_jan09a

    Reply
  68. Dejan,
    A very good project.
    I have been having a great time setting it all up and learning some of the finer details of “Processing”.
    Well done!

    I did notice that the serial communication would fail sometimes when stopping and starting “Processing”. It is likely to be a problem with the string handling if a part message is received and the resulting string length is 0.

    I modified the code so that it looks for a string of at least 4 characters before the “.” (ie 15,0.)


    data = myPort.readStringUntil(‘.’);
    if (data.length()>4) { //check to see if there are enough characters(ie min “15,0.”)

    existing code

    }
    }

    This seemed to make the serial link much more reliable.

    There are many other ways of handling the exception but this was simple to do 🙂

    Cheers
    MOC

    Reply
  69. Hi man i need your help you here. What if i want to add some active buzzer and LED to your code, i tried once and the servo turn really slow. Can you teach me the code so i can add the buzzer and LED?

    Reply
    • Looks like a managed to fix the problem in arduino and now i can works normally. The problem now is with the processing. if i use you code, it’s fine processing draw the sonar, but when i add the buzzer and LED the processing wont draw the sonar

      Reply
  70. Hey.. I followed your steps and have completed the project . After uploading the sketch on arduino i’m getting output on the serial monitor but i am not able to get any output on processing ide. The radar sticks to a fixed point (at zero) , it doesn’t move in sync with the motor. Any solutions for this?

    Reply
      • No error message at all. The radar screen shows up but everything is still, no movement is shown in the radar even though the setup is working fine.

        Reply
      • I have one more question. I am using an arduino uno r3 board so is there any possibility that this might be the reason why it is not working. I have cross checked every connection and now the servo is also not moving .

        Reply
      • servo started moving .Actually it was the wight of the support i made for the sensor because of which it was not moving. Also i am not using a breadboard for connections.The servo is connected to the 5v pin of arduino and the sensor is connected to 9v battery.

        Reply
    • Well yes, it is possible. You will have to modify that part of the code and instead of using line(), use ellipse(a, b, c, d). a,b – x,y coordinates of the ellipse, c,d – width and height of the ellipse.

      Reply
  71. I didn’t realize the Processing code needed to be executed in a download from processing.org. Other than that, my son and I very much enjoyed this build. Thank you.

    Reply
  72. Hey.. I done what you have shown. But I’m not getting the output. In processing windows the scale o radar sticks in ZERO. It doesn’t move any where. Can you help me to fix this.

    Reply
    • Well if you use the updated processing code, which can be found at the bottom of the post, it can fit any screen resolution. You just have to change the parameters for the screen resolution to your screen resolution.

      Reply
    • You don’t have to use that font. If this problem occurs when running the Processing sketch this could help you:
      The problem could be that you should first generate the font in the Processing IDE. Tools > Create Font… and here select that font and size. This will generate appropriate font file in the working directory so that you are able to use that font.
      OR you can just remove these lines in the code and the processing will use its default font.

      Reply
    • Thanks for the comment! Well yes you are right. My tutorials and projects are free so everyone can use them, but if someone use them on other website, just like you said, hi should provide links to the original article. What’s more, he is even using my photos with blurring my logo.

      Reply
  73. Hi. I’m building this Radar for an experiment for school. Is the code compatible with Arduino UNO too? And then , the last code , must be put into Processing IDE , and not other languages , right?
    Thank you

    Reply
      • Dear sir,
        please help me understand what is the problem with my project.
        I followed the steps that u showed in ur video. it was a wonderful project.
        I copied the code for the arduino from this website and it works perfect. the ultra sonic sensor nicely represents the distance and angle in the arduino serial monitor. the problem is with the processing code. when I run the code from my processor IDE it says that there is some error. my processing IDE is version is 1.5.1 I hope for ur help and co operation
        thank u very much

        Reply
  74. Hi sir.

    Actually we’re doing this project in our high school, so we need the link of the original project. We haven’t got much time for do it, so please, try to repair it as soon as you can.

    Thanks for your attention.

    Reply

Leave a Comment