**DETERMINE DISTANCE TO AN OBJECT WITH ULTRA SONIC SENSOR** Emma-sophie Andersen (ea224vz) # **Overview** In this tutorial you'll learn how to use an Ultrasonic sensor (HC-SR04) with in ESP32 board. The ultrasonic sensor can be used to determine the distance to an object contactless. After you have followed this tutorial you will know and understand: * How to wire the sensor to the ESP32 board * Determine the distance to an object using the HC-SR04 ultrasonic sensor with the Arduino IDE extention in VS Code. * Read data via UCB Connection and sent it to ubidots via MQTT protocol. The time it takes to finish this project depends on your level of programming skills and previous experience with IoT. Approximately between 4-8 hours. # **OBJECTIVE** After a few years with software development, this is my first project created with a combination of software and hardware components. I have never developed anything of IoT and chose this project as a starter project to get a fundamental understanding on the topic and the relation between software and hardware. The project has no direct purpose besides measurering distance and that it is fun to play around with. The idea was not to build a final product during this course, rather to learn about IoT. # **LIST OF MATERIALS** Parts can be bought seperate at various stores but I got them as a part of a kit I bought on Amazon for $35.95. Link to product [HERE](https://www.amazon.com/ESP32-WROVER-Contained-Compatible-Bluetooth-Tutorials/dp/B09BC5B4H6?psc=1&pd_rd_w=hmPDy&content-id=amzn1.sym.9b6c7c5b-711f-47e9-8510-2ca3ff59483f&pf_rd_p=9b6c7c5b-711f-47e9-8510-2ca3ff59483f&pf_rd_r=EJP1G4VXC12FB0CAPS7X&pd_rd_wg=4zVEK&pd_rd_r=bdfe4fa1-de12-4aa8-b7f9-e68dafe375f0&ref_=sspa_dk_rhf_yoy_pt_sub_0&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEzVUFGUjRSWExOWlNJJmVuY3J5cHRlZElkPUEwMjI4ODEwMVRRTFFERDJTN0tLQyZlbmNyeXB0ZWRBZElkPUEwODMwODQ0MjNXNUwxQjZMWTRLOSZ3aWRnZXROYW1lPXNwX3JoZl95b3kmYWN0aW9uPWNsaWNrUmVkaXJlY3QmZG9Ob3RMb2dDbGljaz10cnVl) | Item | Description | |:-------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | HC-SR04 Ultrasonic Sensor ![](https://i.imgur.com/fYggWDY.png) | The HC-SR04 module includes an ultrasonic transmitter, a receiver and a control circuit. | | ESP32 Wrover Dev ![](https://i.imgur.com/5C5MaNI.png) | ESP32 is a low-cost, low-power system on a chip (SoC) series with Wi-Fi & dual-mode Bluetooth capabilities. | | Breadboard ![](https://i.imgur.com/DtF1F0g.png) | A board on which you can build electronic circuits without soldering. | | Micro USB cable![](https://i.imgur.com/xxkxuZH.png) | The micro USB cable provides a standard USB 2.0 connector on one end and a Micro USB connector on the other. | | ESP32 GPIO Extension board ![](https://i.imgur.com/SiUY2AP.png)| Used to lead out pins of the ESP32 board to breadboard to avoid GPIO damage. | | Jumper wires ![](https://i.imgur.com/wUPLjzh.png) | Used for making connections between components on your breadboard and your esp32 pins. | # **COMPUTER SETUP** I am using the Arduino IDE with the ESP32 board with a windows computer. This tutorial will not cover how it is done with either MAC or Linux. 1) Connect the ESP32 board to your computer. This is done by using the micro USB vable and plug it into the computers USB port. 2) Download tge Arduino IDE. You can download it [HERE](https://www.arduino.cc/en/software). 3) Install the ESP32 playform to the Arduino IDE. STEP 1) In the Arduino IDE; **File > Preferences**. Step 2) In the "Additional Board Manager URL" enter the following: `https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json` and then click **OK**. 4) Open Boards Manager: **Tools > Board > Boards Manager...** and search for **ESP32 by Espressif Systems**. Now it should be installed! Great work so far! 5) Restart the Arduino IDE. After this go to **Tools > Board** and choose **ESP32 Dev Module**. 6) It is essential for us to be able to communicate with the ESP32 baord. Go to **Tools > Port > *"SELECT YOUR PORT FOR DEVICE"*** 7) Download PubSubClient from [HERE](https://www.arduinolibraries.info/libraries/pub-sub-client). 8) Download Ubidots ESP MQTT library from [HERE](https://www.arduinolibraries.info/libraries/ubidots-mqtt-for-esp8266). Alright, it is now time to send some data! 9) After writing your code, verify the Arduino IDE by pressing Check Mark in the top left corner of the IDE. 10) The code need to be uploaded into your ESP32 Dev Module. Click the icon presenting an arrow pointing right. 11) Open the Serial monitor by clicking the maginifying glass icon in the top right corner. You can now see the logs of your connection, It should look like this: ![](https://i.imgur.com/unOycWl.png) 12) Create an user at Ubidots and log in. 13) If you have entered your wifi credentials in the code and followed the previous steps, you should now see your ESP32 board as a device in your Ubodots accounts. ![](https://i.imgur.com/sKP8ojX.png) Also inside the device, you will see the variable Distance. Here is a nother tutorial on how to manage your Device name and variables: [HERE](https://help.ubidots.com/en/articles/736670-how-to-adjust-the-device-name-and-variable-name?_gl=1*yx61h*_ga*MTgwNzg4MzE5MC4xNjU2NDM4Nzgx*_ga_VEME7QQ5EZ*MTY1Njc1NzE0OS4yLjEuMTY1Njc1NzE5NS4w). Publishing and Subscription of data from and to Ubidots is now possible! To show Data in Ubidots, you need to set a label. The label should be for the distanceInCM (see code). You can follow this easy tutorial on how to do that: [Ubidots tutorial for dashboards](https://help.ubidots.com/en/articles/2400308-create-dashboards-and-widgets). # **PUTTING EVERYTHING TOGETHER** ![](https://i.imgur.com/c45C4Lc.png) * VCC to 3.3V (depending on your board, it could be 5v as well) * GND to Ground (GND) * Trigger (trig) to 2 * Echo to 5. All of the compotents in the image is placed on the breadboard. Connect your board to the computer with the micro USB cable. # **PLATFORM** I chose to work with Ubidots which is a clooud based platform. See their webwite [HERE](https://ubidots.com/). I chose this as it offer a free version and have a simple iterface which was fast to learn and get comfortable with. Their website explains everything very simple and it had some good reviews for beginners. Also, this platforms works for communication with both esp32 USB Cable and MQTT. Their might be some equivalent platsforms to choose from, but I went after something that would be easy and fast to learn. # **THE CODE** First Ill go through the code for the Distance measurement with the HC-SR04 ultrasonic sensor. Afterwards Ill go through the code for connecting to Ubidots. First we definde our variables. Explanations is shown as comments after '//' : ``` const int triggerPin = 5; // GPIO 5 const int echoPin = 18; // GPIO 18 #define SOUND_SPEED 0.034 // saves the velocity of sound in the air at 20ºC. The variable is in cm/uS #define CM_TO_INCH 0.393701 // Allows us to convert distance in centimeters to inches. long duration; // Saves the travel time of the ultrasonic waves (time elasped since transmission and reception of the pulse wave) float distanceInCm; // Saves the distance to an object in cantimeters float distanceInInch; // Saves the distance to an object in inches ``` Then we need to initialize a serial communication so that we can print the measurements. This is being done in the **setup()** function: ``` void setup() { Serial.begin(115200); //Starts the serial communication at a baud rate of 115200. pinMode(triggerPin, OUTPUT); //Sets the triggerPin as an Output - The trigger pin emits the ultasound. pinMode(echoPin, INPUT); //Sets the echoPin as an Input - the echo pin recieves the reflected wave and sends a signal to the ESP32 that is proportional to the travel time. } ``` Are program need to update our data and being able to change and respond, i.e. actively control the board. This is being done in the **loop()** function: ``` /// // The following code produces a 10uS @HIGH pulse on the trigger pin - this means the pin will emit an ultrasound. Before sending the pulse, we give a short @LOW pulse to ensure you'll get a clean @HIGH pulse. /// void loop() { digitalWrite(triggerPin, LOW); delayMicroseconds(2); digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); duration = pulseIn(echoPin, HIGH); //Gets the sound wave travel time. Returns the length of the pulse in microseconds. distanceInCm = duration * SOUND_SPEED / 2; //Calculates the distance to an object distanceInInch = distanceInCm * CM_TO_INCH; //Convert distance to inches - CAN BE EXCLUDED IF YOU ONLY WANT CM. Serial.print("Distance (cm): "); Serial.println(distanceInCm); Serial.print("Distance (inch): "); //CAN BE EXCLUDED IF YOU ONLY WANT CM Serial.println(distanceInInch); //CAN BE EXCLUDED IF YOU ONLY WANT CM delay(1000); } ``` **UBIDOTS CODE** First define the varibales and include library: I have some empty fields here because I do not want to publish these. You should fill them out according to your wifi credentials. it is also important that the token and dive is the same as in Ubidots in order to the MQTT protocol to work. ``` #include "UbidotsEsp32Mqtt.h" const mqtt = require('mqtt'); const char UBIDOTS_TOKEN = ""; // Put here your Ubidots TOKEN const char WIFI_SSID = ""; // Put here your Wi-Fi SSID const char WIFI_PASSWORD = ""; // Put here your Wi-Fi password const char DEVICE_LABEL = "Ultrasonic_Device"; const char VARIABLE_LABEL = "Ultrasonic_LabelCM"; Ubidots ubidots(UBIDOTS_TOKEN); const client = mqtt.connect('mqtt://industrial.api.ubidots.com', {username:token, password:""}); ``` A helping fuction for writing data status ``` byte payload; void callback(char *topic) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < 2; i++) { Serial.print((char)payload[i]); } Serial.println(); } ``` In the setup() you write the code that need to run only one time: ``` ubidots.connectToWifi(WIFI_SSID, WIFI_PASSWORD); ubidots.setCallback(callback); ubidots.setup(); ubidots.reconnect(); ubidots.subscribeLastValue(DEVICE_LABEL, VARIABLE_LABEL); client.publish("esp32/Device", payload); ``` And this is the code that need to loop in the loop() function: ``` if (!ubidots.connected()) { ubidots.reconnect(); ubidots.subscribeLastValue(DEVICE_LABEL, VARIABLE_LABEL); client.subscribe("esp32/output"); } ubidots.loop(); ``` # **TRANSMITTING THE DATA / CONNECTIVITY** The trigger pin is set to HIGH. Because of this, the sensor transmits an ultrasonic burst of eight pulses at 40kHz. This is a eight-pulse pattern that is deisigned so that the receiver do not get “confused” from ambient ultrasonic noice. The ultrasonic oulses goes through the air away from the transmitter. But the echo pin initiate the echo-back signal. If the echo back signals are not reflected back, it goes LOW. (The purple pulses below are the echos) ![](https://i.imgur.com/uYQTcog.png) The duration for the echo signal to remain HIGH, depends on the distance from the HC-SR04 to the object which is placed in front of the sensor. The further away the object is, to longer the signal travels and the longer time it takes. The speed of sound is constant. Data data is being sent every time it gets an echo back. The data is being sent via the MQTT protocol to Ubidots over the Wifi (If you have entered the correct credentials, otherwise it will not work). For me this is being done over 4G IP, I have not tested with 5G but I believe it should work completely fine with 5G as well. The esp32 is connected to the computer with a micro USB cable connection. # **PRESENTING THE DATA** The data can be read directly on the computer monitor with Arduino. But the data is also showed on Ubidots like this: ![](https://i.imgur.com/oC5fBF4.png) Here you can see the latest measured distance form the HC-SR04 which was 55 cm. Ubidots provide several different kind of charts in which your data can be presented, but i did not have time to play around with them so I just wrote it out in plain text *(numbers)*. And here is another example of how it looks on the computer monitor in the IDE: ![](https://i.imgur.com/GV7eEB3.png) ![](https://i.imgur.com/mr8Yot5.png) *The data above is from when I moved a book from a distance, closer towards the sensor.* I have chosen to whow two different measurements as to visualize that it works in different range. # **FINALIZING THE DESIGN** Right now the data is only presented on the computer monitor and ubidots. To finalize the design, you could connect a display (for exmaple an OLED display). This way you can see the measured distance directly on the display instead of on the computer. Overall the project has been educational and fun to create. I have gotten a fundamental understanding on how sensors work and also the concept of IoT. I hope to build upon the project further in the future. The idea for the future is to add the display and change it so that the device can be connected to only a powerbank instead of the computer itself. Unfurtunately I did not have time to do this during the course. Here is the result: *Dont mind the extra compontents on the board, they are not in use. and the cat was 32 cm away from the sensor.* ![](https://i.imgur.com/XBGPGtv.jpg) ![](https://i.imgur.com/yypqd97.jpg) ![](https://i.imgur.com/4ql7aUC.jpg)