Projects

On the Radar

Ultrasonic Radar with Arduino

Victor Casado

Issue 31, February 2020

This article includes additional downloadable resources.
Please log in to access.

Log in

Scan the area around you with this fun to build Arduino Uno based ultrasonic radar.

BUILD TIME: 2 HOURS (PLUS 3D PRINTING TIME)
DIFFICULTY RATING: BEGINNER

Similar to radars that use radio waves and lidars that use light, our project uses ultrasonic sound waves to detect objects around us. We could call it a Sonar seeing that it is using sound, however, sonars are generally considered for use underwater, and the maker world still refer to these as radar.

We see LIDARs that use lasers commonly used in robotics and autonomous vehicles these days, but this is difficult to replicate on the home maker’s workbench. Instead, we’ll use commonly available components, including an Arduino UNO, a servo motor and two ultrasonic modules to build a radar. We’ll combine these with a 3D printed case and custom-written application for a fun project to map our world in 2D on our computer.

For obvious reasons, this radar isn’t intended to mount on a vehicle, but you can use it to map your room or apply it to your other maker projects. Use it on your small robotic car project to avoid hitting walls or surveillance applications to detect an object being moved in the room, for example.

In this project, we will build a working prototype on a breadboard, explain the theory behind the code, then build a full working project with 3D printed housing and App to see objects detected on a computer screen.

THE BROAD OVERVIEW

The concept is simple. The project uses ultrasonic sensor modules mounted on a servo motor that rotates between 0 and 180°. By using two sensor modules back to back, we can scan the environment much faster compared to making one full rotation. This method also simplifies the design because you don’t have the problem of cables getting tangled around the servo, and also avoids the need for a more expensive servo to complete a 360° revolution.

We use an Arduino compatible Uno to control the servo and to receive the data from both ultrasonic sensors. We use a computer connected to the Uno to process the received data, which it interprets and displays as a 2D image thanks to our software application available in the digital resources.

The project will work with other Arduino development boards, but we have chosen to use an Arduino Uno because it would be a common development board in most maker toolkits.

HOW IT WORKS

Our project uses a commonly available 9g servo motor with 180° rotation, however, almost any 5V servo controlled by PWM will work.

The process starts with a test of the servo rotation. First, it rotates a 0° to 180° and then 180° to 0° to check the correct movement of the headset. The servo then rotates degree by degree so that our two HC-SR04 ultrasonic modules can send and receive any ultrasonic echos to help determine the distance to an object.

This is a similar concept to how a simple Primary RADAR works, which sends an electromagnetic pulse, then it waits until the wave is reflected and received. It counts the time from the emission to the reception, divides it by two (because the wave goes forwards, reflects and come backward, and we are only interested in one of the periods to calculate the distance). Since we know the speed of sound is around 340m per second, we can fairly accurately determine how near or far an object is using the formula: distance = speed x time.

The data from both sensors is sent via USB-Serial communication to an APP on your computer, which stores the data in an array that is interpreted to display a 2D plane.

The Prototype Build:

It is good practice to build a working prototype to prove the concept before attempting to design and build a complete device with an enclosure. Let’s first set up the circuit on a breadboard, program the Arduino Uno, and ensure that everything works correctly.

Wire up your prototype by following the Fritzing diagram shown here. Plug to socket jumper wires are needed to connect the ultrasonic sensors to the breadboard. Plug to plug jumper wires are used to connect the servo and Uno to the breadboard. The colours of the wires you use don’t particularly matter, but it is best to use red wires for positive and black wires for negative to help with any troubleshooting if the circuit doesn’t work when you power it up.

Note: You can use just one ultrasonic sensor module to see if the code works, however, you will need to delete or comment out the second sensor’s code. You may see inconsistent data in the serial monitor if you don’t do this.

Once you have the electronics wiring complete, the next step is to program the Uno board with the code that is available from our website.

PROGRAMMING

We will assume this is the first time you have used an Arduino development board, so we will take you step by step.

Before we start, you need to download a file from GitHub. We will explain this further in The Code section, however, for now you just need to download the file to your computer.

STEP 1.

Go to the following GitHub page: https://github.com/Martinsos/arduino-lib-hc-sr04

Select the ‘Clone or download’ button and choose ‘Download ZIP’ to download the file to your computer.

Step 2.

If not done so already, install Arduino IDE application onto your computer and launch the program. https://www.arduino.cc/en/Main/Software

Step 3.

Connect your Arduino Uno board to an available USB port on your computer using a USB cable. The power light on the Arduino board should light up, and a second LED will begin to flash slowly.

Step 4.

From the Arduino IDE main menu, select Tools > Board and choose Arduino/Genuino Uno, if not selected already.

Step 5.

From the main menu, select Tools > Port and choose the port that your Arduino is plugged into.

STEP 6.

To add the library we downloaded in Step 1, go to the menu in the Arduino IDE, choose Sketch, Include Library, and select Add .ZIP Library.

Find and select the ZIP file you downloaded. The Arduino IDE should state “Library added to your libraries” when this is complete.

Parts Required:Jaycar
1 × Arduino Uno or Compatible BoardXC4410
1 x USB Cable for Arduino Uno (if required)WC7705
1 × SG90 Servo MotorYM2758
2 × Ultrasonic ModulesXC4442
1 x Pack of Plug to Socket Jumper LeadsWC6028
1 x Pack of Plug to Plug Jumper LeadsWC6027
1 × Small Prototyping BreadboardPB8820

Step 7.

Open the code that you have downloaded from our website, by choosing File > Open. Navigate to the Ultrasonic_Radar_Code.ino file on your computer and select Open.

The code, called a sketch, should appear in the Arduino IDE window.

Step 8.

To upload this code (called a sketch) to the Arduino Uno board, select the Upload icon. The message “Done uploading” will show if successful. At the same time, the servo should rotate 180° and then slowly travel back and forth.

Step 9.

Open up the Serial Monitor pop-up window by going to Tools > Serial Monitor from the main menu, or by selecting the icon in the top right corner of the IDE screen.

Step 10.

You should now see numbers scrolling automatically in the Serial Monitor window. The first value is the servo’s position that cycles between 0 and 180 as the servo moves. The two other values are the measurements from each ultrasonic module.

As you place your hand or an object in front of the ultrasonic sensors you will notice these ultrasonic values decrease. They should go to almost 0 if your hand covers the sensors.

If you notice a significant difference between the two ultrasonic values with your hand at the same distance from them, it could be because of different tolerances on the HC-SR04 board. To help fix this discrepancy, the line in the Arduino Code “d = t / 59;” can be adjusted. For example. if the sensor reports half of the distance you have your hand away from the sensor, then change the 59 by 29, or if it reports you double the distance, then change the 59 by a 119. It may take some trial and error for the optimum setting.

Note: When designing this project, we found that the range of the sensors varied significantly depending on the manufacturer. For example, the first build with two sensors had correct measurements up to 2.5 metres, but another build using different sensor modules could only “see” up to 1,2 metres away. So, the maximum range your sensor measures is likely dependent on the quality of your HC-SR04.

If your Serial Monitor shows the scrolling data as we describe above, you have successfully completed the prototype. Well done.

In next month’s issue, we will show you how to turn the prototype into a full build with 3D printed enclosure and provide an App for your computer to map your room in 2D. For now, you can learn how the code works over the following pages.

THE CODE

The code is divided into two parts; the Arduino code and the Processing APP code that we will describe after the build.

The Arduino code has been made available for you to download from our website. We have commented each line of code to help you with troubleshooting or modifying the code to suit your application, if necessary.

For our project, we are going to power, program and send/receive data from the Arduino through the USB-Serial port. You could possibly expand your project to interface directly with a Smartphone with some added hardware, however, this is beyond the scope of this project.

First, we call the servo.h and HCSR04.h libraries, which allows us to control our servos and interfaces easily with the HC-SR04 sensors.

#include <HCSR04.h>
#include <Servo.h>

We then create the objects of the two sensors and the servo. This method of object oriented programming helps make the code cleaner and easier to understand.

UltraSonicDistanceSensor distanceSensor(6, 7);
UltraSonicDistanceSensor distanceSensor2(5, 4);
Servo servoMotor;

We create three variables. The first one is a delay time (in ms) that we are going to use to wait for the servo motors to reach the 1 degree increments, You can increase this if you want the servo movement to work faster or decrease to slow it down. Too low though and the servo will block. The two other variables, d and d2, will store the distance data received from the sensors.

int delayTime = 5;
long d; 
long d2; 

SETUP

We first initialise the serial communication at a 9600 baud rate. Then the following code assigns digital PWM pin 2 on our Uno to control our servo, and make the servo rotate a 180° and back again with a short delay in between.

  servoMotor.attach(2);
  servoMotor.write(180);
  delay(1000);
  servoMotor.write(0);
  delay(1000);

LOOP

The Loop code is a little long to put here, however if you review it in the file you'll see it moves the servo either forwards in 1° increments up to 180° or in reverse until it gets to 0°. With each 1° step, measurements are taken from the sensors and data is sent and printed via the serial monitor. This repeats continuously.

The data is displayed as ANGLE, DISTANCE1, DISTANCE2n.

3D PRINTED ENCLOSURE

For the main build, there are four parts need to be printed for this project. We used a Flashforge Creator Pro to print the project described here.

1. HEADSET

This is where the two ultrasonic modules fit. You will need to gently cut out the supports from the four holes, and you may need to file the holes, just enough to get the ultrasonics to friction fit.

2. HEADSET BASE

This piece is designed to fit into the headset, and glued in place.

3. THE BOX

Houses the Uno board and wiring. The USB port may need to be filed slightly for the Uno board to fit.

4. THE BOX CAP

Fits on top of the box with the servo attached. Two pilot holes are included to help secure the servo to the cap.

The Main Build:

Additional Parts Required:Jaycar
4 × M3 x 8mm Screws*^HP0403
4 x M3 Nuts*HP0425
4 x M4 x 10mm Screws*HP0450

* Quantity required, may only be supplied in packs

^ 10mm long screws will also work but will protrude from the bottom of the case.

First, we recommend you to start printing the 3D parts so you can build the electronics and program your board while the parts are being printed. Depending on your printer and settings, it may take some time to print. In our case, it took around 10 hours to print all the parts,

Before you start construction, prepare cables with a length shorter than 10 centimetres (the shorter, the better) to fit inside the enclosure. If the cables are too long, you may restrict the movement of the headset.

To build the electronics, take the Arduino Uno, the servo and the ultrasonic sensors and wire them as shown. Don’t solder the sensors just yet, because you will have to pass the wires through the 3D printed headset cap.

CONSTRUCTION

With the electronics prepared, we can now go ahead and install the components into the enclosure.

Start by installing the Uno board into the box. Secure it with four M3 x 8mm screws and nuts.

If your ultrasonic sensors have their pinout connections at 90°, you will need to gently bend them straight with some pliers so they point directly outward from the PCB.

Connect short leads with header sockets onto both ultrasonic sensors (Now is a good time to write down what colour wires are going to which pin). Insert the sensors into the 3D printed headset enclosure. They should friction fit. If they are loose, you could add some plastic friendly adhesive.

To avoid restricting the movement of the servo, it is best to use flexible leads. If you are using ribbon-type cable, separate each strand to help the wires become more flexible.

Pass the wires from each sensor through the 3D printed headset base and glue into place. We recommend mounting the semicircle gap perpendicular to the sensors so the cables are free to move easily when the headset rotates.

Mount the servo onto the 3D printed case lid using the screws supplied with the servo or with glue. Make sure you mount it from the drive shaft closer to the centre of the lid.

Pass the wiring from both ultrasonic sensors through the lid (from the side that has the servo drive shaft).

The headset should friction fit tightly onto the servo’s drive shaft (If not, see our troubleshooting section).

If you are certain your servo is in the 0° position, you can align the headset to the case as you see in this diagram. i.e. 90° between the semicircles. If you are unsure of your servo’s position, you can re-adjust after we’ve powered it up in the testing stage.

We can now move onto completing the wiring and connecting it to the Uno board.

It is best to use a soldering iron to connect the wires together and use electrical tape or heatshrink to cover any exposed wires. Keep in mind to keep leads short because there isn’t a lot of room inside the case and too much wiring may impede the servo’s travel.

  • Join the two Vcc from the ultrasonic sensors and the positive from the servo to a male header
  • Join the two GND from the ultrasonic sensors and the negative from the servo to a male header
  • Join the orange wire from the servo to a male header
  • You should also have two pairs of signal wires from each ultrasonic sensor

Refer to the wiring diagram to confirm you have wired it correctly. Next, follow these steps to connect the wiring to your Uno board:

  • Lead from the servo to pin 2 of the Uno
  • Positive lead to 5V on the Uno
  • Negative lead to GND on the Uno
  • Connect the Trig leads and Echo leads to Uno pins 4, 5, 6 & 7 (Refer to the Fritzing diagram to make sure the leads from the sensor go to the correct pins on the Uno).

With the wiring complete, you can now gently put the headset on the box, slowly feeding the wiring into the case as you go. Fix the lid to the case using 4 x M4 screws. The lid has also been designed to attach using 45mm long x 3mm screws.

INSTALLING & USING THE APP

Code for the App can be downloaded from our website. To use that code, we need to install a software application called ‘Processing’, which is a free and open source software sketchbook, and a language for learning how to code with visual output.

STEP 1.

Go to: https://processing.org/download/ and download and install the application that suits your operating system. Then, launch the Processing program.

STEP 2.

Open the Radar_App.pde file that is available for download from our website. Then, press the Run icon, which will launch a pop-up window for the radar application.

STEP 3.

The application will prompt you for the COM port that your Arduino Uno is connected to and give you a list of options (a, b, c, etc.). If you are unsure, you could look at the port that your Arduino IDE is connected to by going to Tools > Port in the Arduino IDE application.

Note that you can’t have Arduino IDE with the prototype code running at the same time. You will need to close the Arduino IDE if you see an error message.

You should now see a pop-up screen with a green radar graphic. The servo should start to move, and small blue dots should sweep across the radar screen as objects are detected in front of the ultrasonics. Success!

You may notice the servo speeds up when an object gets closer, which is related to the loop code. In short, the Arduino sends a pulse and waits for it, and if an object gets closer, the wait to receive the sound will be shorter. This makes the for loop jump to the next step sooner, making the servo travel sooner.

THE PROCESSING CODE

The App takes the data from the serial port and stores it in an array. To display the data, we use what mathematicians call curve parametrization, which is a powerful method to get the cartesian coordinates of a curve with an angle and a distance. In this case, the parametrization of a circumference is:

x = r * cos(a);

y = r * sin(a);

Where (x,y) are the two-dimensional cartesian coordinates of the point. r is the distance, and a is the angle. This is also called Polar to Cartesian Coordinates Conversion.

TROUBLESHOOTING

If you find the servo/headset isn’t travelling smoothly or not performing a complete 180° arc, it could be because the headset printed enclosure base is slipping on the servo drive shaft. If this is happening to you, you could add a little glue to fix the drive shaft to the printed base or attach a server horn, as shown here.

WHERE TO FROM HERE?

This project has many ways it could be improved. If you’re handy with 3D printing, you could change the design of the box and headset pieces for a different appearance. Make sure the headset isn’t too heavy because it may make it difficult for the servo to work.

A code savvy maker could improve how the App works, from changing colours of the text, radar rings, etc. The colours can be changed in the lines that call the Fill() function, where it has red, green, blue and in some cases, a fourth argument for the alpha channel. Perhaps the code could be updated to change colours or make noises when an object gets too close to the sensors.

Another idea could be to add a six or nine degree of freedom IMU. For example, if you attach a sensor like the MPU6050 in the box under the servo, you could then send the Yaw Axis rotation through the USB-Serial with the distances data. This would help you make corrections when displaying the data, so you can get more accurate measurements. Or, you could make the 2D representation of the Processing App to rotate, so you can get a visual representation of how the device, let’s say a robot, is rotating in the environment, something like a compass.