You are currently viewing Arduino Radar using Ultrasonic Sensor HC-SR04 DIY Kit

Arduino Radar using Ultrasonic Sensor HC-SR04 DIY Kit

SuperKitz.com ​Project Manual

Arduino Radar using Ultrasonic Sensor HC-SR04 DIY Kit

Using Arduino Nano and Arduino Radar using Ultrasonic Sensor HC-SR04

In this project, we are about to design a simple radar using an ultrasonic sensor with an Arduino board. All you need for this project is an ultrasonic sensor for detecting the object in its range, a small hobbyist sg90 Servo Motor for rotating the sensor, and an Arduino board for controlling them.

Requirements :
● Computer with an internet connection

● Download and install Arduino IDE

● Download and install processing ide

Components

Arduino NANO

Jumper wires

Ultrasonic Distance Sensor HC SR04

Ultrasonic Sensor HC-SR04

Micro Servo Motor SG90

Hardware

ARDUINO NANO

The Arduino Nano is basically a mini arduino uno which has all the capabilities as it is also made with the came chip atmega328 but in a SMD package .We are able to connect and give power to it through the MINI-B usb cable port.

Another wonderful feature of the arduino is the option of using a add-on boards to the arduino which comes as a module and they are known as “Shields”

Pin out diagram
Arduino Nano

Ultrasonic Sensor HC-SR04 (Distance Measurement)

Ultrasonic Distance Sensor HC SR04

An ultrasonic sensor  detects and measures the distance of a target object using ultrasonic sound waves and converts the reflected sound into an electrical signal.

  • 5V and 2 mA
  • 0.3 cm resolution
  • 2 to 450 cm Detection range

 

The ultrasonic sensor has 4 pins which are VCC , TRIG , ECHO , GND .The two main components of this sensor is the transmitter and receiver where the transmitter produces the sound and the receiver ,receives it

The voltage pin VCC is connected to 5V and the GND is connected to ground and the trig and echo is connected to the gpio pins

Ultrasonic Sensor HC-SR04 uses sonar to measure the distance of the object. It emits an ultrasonic wave at 40000HZ which will go and bounce back after hitting an object .The time travelled and the speed of the sound, we can calculate distance (speed=distance/time). Ultrasonic waves are much more faster than regular sound and as humans we wont be able to hear it.(some animals and fishes like the dolphins and bats are able to use it for communication and seeing in the dark)

To generate the ultrasound, the Trig is set to a high state for a time of 10 µs, in response to it sensor transmits an 8 cycle sonic burst at 40KHz which will travel at the speed sound and it will be received in the Echo pin. The Echo pin goes high and will output the time in microseconds of the sound wave traveled. As soon as the signal is received the echo pin goes low.

Consider an object 10 cm away from the sensor, travelling at a  speed of  340 m/s or 0.034 cm/µs, the sound wave will need to travel about 294 u seconds. But the Echo pin generates an output double that number because the sound wave needs to travel forward and bounce backward. So the distance in cm is calculated by multiplying the received travel time value from the echo pin by 0.034 and divide it by 2.

Micro Servo Motor

Micro servo motors provide precise control of linear and angular position, velocity, and acceleration. They are useful in many robotics projects, such as for turning the front wheels on an RC model for steering or pivoting a sensor to look around on a robotic vehicle.

Servo is a general term for a closed-loop control system which consists of a suitable motor, couple to a sensor for position feedback signal, in order to adjust the speed and direction of the motor and to achieve the desired result

RC servo motor works on the same principle. A DC motor is connected to the output shaft through the gears.
A servo motor works with a small DC motor connected to the output shaft through the gears. The output shaft drives a servo arm which is connected to the potentiometer (pot). The potentiometer provides position feedback to the servo control unit where the current position of the motor compared to the target position.
The control unit corrects the actual position of the motor according to the error so that it matches the target position.

How Servo Motors Work?

A servo motor can be controlled by sending a series of signal pulses to the signal. A conventional analog servo motor can receive a pulse roughly every 20 milliseconds (i.e. signal should be 50Hz). The position of the servo motor determines the length of the pulse.

  • If the pulse is high for 1ms, then the servo angle will be zero.
  • If the pulse is high for 1.5ms, then the servo will be in its center position.
  • If the pulse is high for 2ms, then the servo will be at 180 degrees.

In this servo motor, the pulses ranging between 1ms and 2ms will rotate the servo shaft to full 180 degrees of its travel.

 

Circuit Diagram

STEP1: CONNECTING Ultrasonic Sensor and servomotor To ARDUINO 

  • Connect VCC of servomotor(red wire) and VCC of the ultrasonic sensor to 5v of Arduino
  • connect the gnd of ultrasonic sensor and servo(black wire) to the ground of the Arduino
  • connect trig and echo pin of the ultrasonic sensor to 8 and 7 of Arduino.
  • connect signal pin of the servo to pin 9 of Arduino.

Building the device

Note:  Here Is how we build it.

  • Firstly, a cardboard stand is made for connecting the Ultrasonic sensor to the Servo motor.
  • I folded it like it’s shown in the picture below, glued it, and using a screw, I fix the servo motor to it.
  • Finally using an elastic band the servo motor is secured to Arduino
Step 1
Step 2
Step 3
Step 4

Getting started with Arduino

Before starting any project, we need to interface Arduino with a computer. So we have to write and compile code for the Arduino to execute, as well as providing Arduino to function with the computer.

Installing The Arduino Software Package On Windows

Download a version of Arduino software suitable for your version of Windows from Arduino website / superkitzs.com. After downloading, check the instructions below to install the Arduino Integrated Development Environment (IDE).

 

 

Connect your Uno board with an A B USB cable; sometimes this cable is called a USB printer cable

In order to program the board, the USB connection with the PC is necessary to program the board and not just to power it up. The Arduino Uno is capable of withdrawing power from either the USB or an external power supply. Connect the board to your computer using the USB cable. The green power LED (labeled PWR) should go on.

If you used the Installer, as soon as you connect your board the Windows – from XP up to 10 – will install drivers automatically

If the board is not properly recognized when the zip package is downloaded and expanded, please follow the procedure below.

  • START menu> CONTROL PANEL MENU
  • From the control panel, check for System and Security
  • Select system
  • Select Device Manager from the System window
  • Select open port named “Arduino UNO (COMxx)”, under Ports (COM & LPT). If there is no COM & LPT section, check “Other Devices” for “Unknown Device”.
  • Choose the “Update Driver Software” option by right-clicking on the “Arduino UNO (COmxx)” port
  • Navigate to the “Browse my computer for Driver software” option.
  • Choose the driver file named “arduino. inf”, located in the “Drivers” folder of the Arduino Software download (not the “FTDI USB Drivers” sub-directory). If you are using an old version of the IDE (1.0.3 or older), Choose the Uno driver file named “Arduino UNO.inf”, If an old version of the IDE (1.0.3 or older) is used
  • Thus the windows driver installation is completed

Select your board type : Arduino Nano  and port

Choose Tools | Serial Port menu. This is likely to be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect your board and re-open the menu; the entry that disappears should be the Arduino board. Reconnect the board and select that serial port.

Getting started with Arduino

About Processing

Processing is a great source for creating graphics. The Processing IDE is similar to that of Arduino in terms of structure. Unlike Arduino has a setup and loop function, it has set up functions and draw functions. The Processing IDE can communicate with the Arduino IDE through serial communication. This way, the data is transmitted from the Arduino to the Processing IDE and also from the Processing IDE to the Arduino.

  • Paste the given code in processing ide
  • Run the processing ide.
  • com3 port on the code to your com port to which Arduino ide is connected has to be changed
  • To know which com port you are connected to follows the image.

 

 

Installing Processing

If you do not have already installed the Processing IDE, then you need to install it first. To install it, go to the link below and download the latest version of processing IDE. https://processing.org/download/or https://www.superkitz.com/home/dh_3j3yy4/superkitz.com/libraries/processing-3.5.4-windows64.zip

After downloading the latest version, open the Processing IDE setup and install it. After installing, open the Processing IDE and you will see something like this.


Press CNTRL + A and press DELETE on keyboard for clearing the Arduino IDE page

Upload the program to Arduino 

Copy the Sketch Code given below And try to understand 

After that click on the “Upload” button. Then we can see the RX and TX LED on the board flashing. The message “Done uploading.” will appear if the uploading is a success

The pin LED on the board start to blink (in orange) soon after the upload finishes. If it does, congratulations, it resembles that Arduino up-and-running. Refer to the troubleshooting suggestions if there is an error.


Arduino Source Code

#include <Servo.h>. 

const int trigPin = 8;
const int echoPin = 7;

long duration;
int distance;
Servo myServo;
void setup() {
  pinMode(trigPin, OUTPUT); 
  pinMode(echoPin, INPUT); 
  pinMode(4,OUTPUT);
  pinMode(11,OUTPUT);
  Serial.begin(9600);
  myServo.attach(9); 
}
void loop() {
  
  for(int i=0;i<=180;i++){  
  myServo.write(i);
  delay(30);
  distance = calculateDistance();
  
  Serial.print(i); 
  Serial.print(","); 
  Serial.print(distance);
  Serial.print("."); 
  }
  
  for(int i=180;i>0;i--){  
  myServo.write(i);
  delay(30);
  distance = calculateDistance();
  Serial.print(i);
  Serial.print(",");
  Serial.print(distance);
  Serial.print(".");
  }
}

int calculateDistance(){ 
  
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
  
  digitalWrite(trigPin, HIGH); 
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance= duration*0.034/2;
  if (distance < 40)
    {
      digitalWrite(4,HIGH);
        digitalWrite(11,HIGH);
      
    }
    else
    {
      digitalWrite(4,LOW);
        digitalWrite(11,LOW);
    }
     return distance;
  
 
} 

Interfacing with  Processing

Using the serialevent() function  we will receive the values for the angle and the distance measured by the sensor from the Arduino Board into the Processing IDE. This 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. Finally, these variables 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.

Processing Source Code

/*
Radar Screen Visualisation for HC-SR04
Maps out an area of what the HC-SR04 sees from a top down view.
Takes and displays 2 readings, one left to right and one right to left.
Displays an average of the 2 readings
Displays motion alert if there is a large difference between the 2 values.
*/
import processing.serial.*;     // import serial library
Serial arduinoport;                  // declare a serial port
float x, y;                       // variable to store x and y co-ordinates for vertices   
int radius = 350;               // set the radius of objects
int w = 300;                    // set an arbitary width value
int degree = 0;                 // servo position in degrees
int value = 0;                  // value from sensor
int motion = 0;                 // value to store which way the servo is panning
int[] newValue = new int[181];  // create an array to store each new sensor value for each servo position
int[] oldValue = new int[181];  // create an array to store the previous values.
PFont myFont;                   // setup fonts in Processing
int radarDist = 0;              // set value to configure Radar distance labels
int firstRun = 0;               // value to ignore triggering motion on the first 2 servo sweeps
/* create background and serial buffer */
void setup(){
// setup the background size, colour and font.
size(1204, 650);
background (0); // 0 = black
myFont = createFont("verdana", 12);
textFont(myFont);
// setup the serial port and buffer
arduinoport = new Serial(this, "COM4", 9600);
}

/* draw the screen */
void draw(){
fill(0);                              // set the following shapes to be black
noStroke();                           // set the following shapes to have no outline
ellipse(radius, radius, 750, 750);    // draw a circle with a width/ height = 750 with its center position (x and y) set by the radius
rectMode(CENTER);                     // set the following rectangle to be drawn around its center
rect(350,402,800,100);                // draw rectangle (x, y, width, height)
if (degree &gt;= 179) {                  // if at the far right then set motion = 1/ true we're about to go right to left
motion = 1;                         // this changes the animation to run right to left
}
if (degree &lt;= 1) {                    // if servo at 0 degrees then we&#039;re about to go left to right
motion = 0;                         // this sets the animation to run left to right
}
/* setup the radar sweep */
/* 
We use trigonmetry to create points around a circle.
So the radius plus the cosine of the servo position converted to radians
Since radians 0 start at 90 degrees we add 180 to make it start from the left
Adding +1 (i) each time through the loops to move 1 degree matching the one degree of servo movement
cos is for the x left to right value and sin calculates the y value
since its a circle we plot our lines and vertices around the start point for everything will always be the center.
*/
strokeWeight(7);                      // set the thickness of the lines
if (motion == 0) {                    // if going left to right
for (int i = 0; i = 0; i--) {     // draw 20 lines with fading colour
stroke(0,200-(10*i), 0);          // using standard RGB values, each between 0 and 255
line(radius, radius, radius + cos(radians(degree+(180+i)))*w, radius + sin(radians(degree+(180+i)))*w);
}
}
/* Setup the shapes made from the sensor values */
noStroke();                           // no outline
/* first sweep */
fill(0,50,0);                         // set the fill colour of the shape (Red, Green, Blue)
beginShape();                         // start drawing shape
for (int i = 0; i &lt; 180; i++) {     // for each degree in the array
x = radius + cos(radians((180+i)))*((oldValue[i])); // create x coordinate
y = radius + sin(radians((180+i)))*((oldValue[i])); // create y coordinate
vertex(x, y);                     // plot vertices
}
endShape();                           // end shape
/* second sweep */
fill(0,110,0);
beginShape();
for (int i = 0; i &lt; 180; i++) {
x = radius + cos(radians((180+i)))*(newValue[i]);
y = radius + sin(radians((180+i)))*(newValue[i]);
vertex(x, y);
}
endShape();
/* average */
fill(0,170,0);
beginShape();
for (int i = 0; i = 360) {
stroke(150,0,0);
strokeWeight(1);
noFill();
for (int i = 0; i  35 || newValue[i] - oldValue[i] &gt; 35) {
x = radius + cos(radians((180+i)))*(newValue[i]);
y = radius + sin(radians((180+i)))*(newValue[i]);
ellipse(x, y, 10, 10); 
}
}
}
/* set the radar distance rings and out put their values, 50, 100, 150 etc.. */
for (int i = 0; i &lt;=6; i++){
noFill();
strokeWeight(1);
stroke(0, 255-(30*i), 0);
ellipse(radius, radius, (100*i), (100*i)); 
fill(0, 100, 0);
noStroke();
text(Integer.toString(radarDist+50), 380, (305-radarDist), 50, 50);
radarDist+=50;
}
radarDist = 0;
/* draw the grid lines on the radar every 30 degrees and write their values 180, 210, 240 etc.. */
for (int i = 0; i = 300) {
text(Integer.toString(180+(30*i)), (radius+10) + cos(radians(180+(30*i)))*(w+10), (radius+10) + sin(radians(180+(30*i)))*(w+10), 25,50);
} else {
text(Integer.toString(180+(30*i)), radius + cos(radians(180+(30*i)))*w, radius + sin(radians(180+(30*i)))*w, 60,40);
}
}
/* Write information text and values. */
noStroke();
fill(0);
rect(350,402,800,100);
fill(0, 100, 0);
text("Degrees: "+Integer.toString(degree), 100, 380, 100, 50);         // use Integet.toString to convert numeric to string as text() only outputs strings
text("Distance: "+Integer.toString(value), 100, 400, 100, 50);         // text(string, x, y, width, height)
text("Radar screen code ", 540, 380, 250, 50);
fill(0);
rect(70,60,150,100);
fill(0, 100, 0); 
text("Screen Key:", 100, 50, 150, 50);
fill(0,50,0);
rect(30,53,10,10);
text("First sweep", 115, 70, 150, 50);
fill(0,110,0);
rect(30,73,10,10);
text("Second sweep", 115, 90, 150, 50);
fill(0,170,0);
rect(30,93,10,10);
text("Average", 115, 110, 150, 50);
noFill();
stroke(150,0,0);
strokeWeight(1);
ellipse(29, 113, 10, 10); 
fill(150,0,0);
text("Motion", 115, 130, 150, 50);
fill(0,450,500);
text("Developed by: SUPERKITZ ", 350, 400, 150, 50);
text("www.superkitz.com ", 400, 430, 150, 50);
fill(0,110,0);
}
/* get values from serial port */
void serialEvent (Serial arduinoport) {
String xString = arduinoport.readStringUntil('\n');  // read the serial port until a new line
if (xString != null) {  // if theres data in between the new lines
xString = trim(xString); // get rid of any whitespace just in case
String getX = xString.substring(1, xString.indexOf("V")); // get the value of the servo position
String getV = xString.substring(xString.indexOf("V")+1, xString.length()); // get the value of the sensor reading
degree = Integer.parseInt(getX); // set the values to variables
value = Integer.parseInt(getV);
oldValue[degree] = newValue[degree]; // store the values in the arrays.
newValue[degree] = value;  
/* sets a counter to allow for the first 2 sweeps of the servo */
firstRun++;
if (firstRun &gt; 360) {
firstRun = 360; // keep the value at 360 
}
}
}
  

Output

When the proximity sensor detects an obstruction it will send angle and distance of obstruction data to processing.

Leave a Reply