In this tutorial, we’ll walk through the creation of a react app that displays real-time information from an ultrasonic sensor connected to the NodeMCU esp8266 board (Wi-Fi module) which sends and stores data in the Firebase database.
The project measures the distance to the water in a tank and sends the information to the database through Wi-Fi so that a web page can be rendered with the distance to the liquid in the tank.
If it seems scary at first, believe me, it’s not. I’ll make it as clear and succinct as possible so that even if you have little to no expertise in the area, you’ll achieve the desired goal.
Github project link.
Feel encouraged to use this guide as support to building your own project. The intent of this guide is the development of a complete IoT project, not its publication.
I’ve divided this tutorial into four parts: Circuit setup, Firebase setup, Arduino code and React app. Let’s get to it!
1. Circuit setup
Before getting started, a few things are required:
- HC-SR04 ultrasonic sensor, which will give us the distance from the sensor to water in the tank.
- NodeMCU ESP8266 board (Wi-Fi module), to read and send the above information to the Firebase database.
- A few Jumper Wires, to connect the components.
- A bucket, I’ll call it a tank to make it fancier.
- Micro USB Cable, to communicate with Arduino IDE on your computer.
- 5V battery, to power the board. (optional).
For the sensor to provide the information needed, which is the water level in the tank, let’s understand how it operates.
The sensor emits a high-frequency sound pulse that propagates through the air with a certain speed. When the pulse reaches an object, an echo signal will be reflected into the sensor.
Considering it’s known when the pulse is emitted and when it’s received back through reflection, this can be used together with the speed of sound in the air to calculate the distance from the sensor to the object.
The formula will look like this:
distance = (speed of sound * elapsed time) / 2
Since the pulse leaves the sensor to reach the object and then returns, it’s value must be divided by two as the total distance it goes through is twice what we want to measure.
Let’s now connect the sensor to the board as shown below.
- Vcc will be connected to the VU pin.
- GND will be connected to any GND pin.
- Trig will be connected to the digital D0 pin as Output.
- Echo will be connected to the digital D1 pin as Input.
Since the ultrasonic sensor needs 4.5V ~ 5.5V to operate and the default output value for the board is 3.3V, a 5V battery can be connected to the VIN input to supply the board with 5V and thus achieve 5V in it’s VU pin.
Instead of the battery, you can also connect the board to your computer through USB, which will supply it with 5V.
IMPORTANT! You must never connect VIN to a power source and connect the USB socket. That can destroy the USB port in your computer since there’s zero back-powering protection on that board.
2. Firebase setup
Setting up an online database is pretty easy with Firebase. The only requirement is a Google account.
Visit the Firebase homepage and hit the GO TO CONSOLE button on the top-right corner of the page. If you are not already signed in, you’ll be prompted to.
Create a new project by clicking Add Project.
You can choose any project name you want, and also set the preferred region.
Now click Database on the left menu and when the page loads, scroll down to Realtime Database. That’s the option you should choose.
Hit Create database and select Start in test mode. This will allow data to be put without worrying about authentication.
Test mode is not recommended if you are going to release your app to the public, which is not the purpose of this guide.
Click Enable to proceed.
Simple as that, your database is ready to be used! To finish this section, you’ll need to save a few information for later usage.
Click the gear icon to the right of Project Overview on the left menu and select Project Settings.
Save Project ID and Web API key values somewhere you can access later.
Now on Service Account, choose Database Secret and hover the dotted sequence to the right of your database name and click show.
Save this Secret Key.
These values will be used on the code for the board and also the web app, enabling a connection to the database for both.
3. Arduino code
It’s coding time! The requirements for this part of the tutorial are:
- Arduino IDE. Download link.
- Firebase Arduino library. Github link.
- Arduino JSON V5.13.1 library (Do not download v6+). Github link.
In case you haven’t used Github before, you just need to click the Firebase Arduino link above, hit the “download or clone” button and choose Download ZIP. As for the Arduino JSON library, I’ve specified a version because the newest one conflicts with the Firebase library. Click the link, scroll to the bottom of the page and hit the ArduinoJson-v5.13.1.zip to download.
Now that you have downloaded the Arduino IDE and the required libraries, let’s configure the environment.
Install the Arduino IDE and launch it.
On the top menu, click Sketch → Include Library → Add .ZIP Library…
and select Firebase Arduino and Arduino JSON files you downloaded.
Installing the board’s configurations is important. For that, click Preferences and paste the following URL to Aditional Boards Manager URLs: https://arduino.esp8266.com/stable/package_esp8266com_index.json
Click Tools → Board → Boards Manager and search for “esp8266” and click the Install button on the one by ESP8266 Community.
Great, now you can start a new project with the current file. Click File → Save and name the project whatever you want, I named it esp_distance_sensor.
Copy and paste the code below to your Arduino project, and change the fields <YOUR_FIREBASE_PROJECT_NAME>,
<YOUR_WIFI_NETWORK_NAME> and <YOUR_WIFI_NETWORK_PASSWORD> to its respective values.
Make sure you remove both “<” and “>” from the values you’ve changed.
With the board connected to your computer through USB, you can now click the right arrow on the top menu of the Arduino IDE to compile and upload the code to the board. Or you can use Sketch → Upload.
Wait until it loads and then choose Tools → Serial Monitor and the distance values should be showing in your screen and also be sent to the database.
The project is pretty much functional by now and we can move to create the web application which will consume and exhibit the distance values that are being stored.
4. React app
The last requirements of this tutorial are:
Download and install Node.js through the provided link, both versions would be fine but if you are not sure, you can go with the “recommended for most users” one. This software includes npm which stands for “node package manager” and is a tool that facilitates the installation of packages that will be used in the project.
react, create-react-app and firebase are examples of packages that we will use, and thanks to npm it is easy to use a CLI (Command Line Interface) such as the mac terminal or cmd.exe to install these dependencies on a project.
You don’t have to mind those terms, but in case you do, I like to explain a little bit of what they are considering when I first started programming I’d face such things and get completely lost.
Open the terminal app if you are using OSX, you can click 🔍 in the upper-right corner of the menu bar, or press Command + Space bar, type “Terminal” and hit enter.
Or the Command Prompt if you are using Windows, click the start button search for cmd.exe and hit enter.
The following code will install through npm a package called “create-react-app” which is a tool to prepare a basic project so that you can jump right into developing the application. Also, -g means it will be installed globally on your machine allowing it to be used on any folder lets say. The next packages you will need will be installed locally only, on the project folder.
Write the code on the terminal/cmd window and hit enter.
npm install -g create-react-app
You may need to write “sudo npm install -g create-react-app” which will await your computer’s password to make such changes as a super user.
Now that this amazing tool is installed, you can type the following code to change the directory to the Documents folder and create a project with the name iot-distance-sensor. You can change that name to whatever you want.
If you don’t use “cd Documents” you will create the project folder on the default location for the terminal, which is likely to be the logged user folder.
When completed, a new folder will appear with the name you’ve chosen.
Let’s proceed with the coding editor. Launch VSCode or another editor you’ve got and choose File → Open … and select the folder that was created by create-react-app.
You should have something like the above image when you open src → App.js on the left menu.
VSCode enables an embedded CLI, which can be accessed by clicking Terminal → New Terminal on the top menu. If you are not using VSCode, you should use the default CLI and make sure you are on the project folder to follow through.
The above code starts a development server on port 3000, so you can see your web application live at localhost:3000.
Also, run the following command to install the packages that will be used:
npm install --save firebase axios
Back to VSCode you can right click and delete App.test.js and logo.svg for they won’t be used.
Right-click src → New File and create canvas.jsx, firebase.jsx, and then style.css.
Below I have included comments on all files explaining what each line of code does since that’s not the main purpose of this guide.
Here, however, I intend to explain what these files do.
firebase.jsx is the file that will establish a connection to the Firebase database, it will be used by our main component to listen to changes on the data of a specific field, in this case, the distance that is being stored.
App.js is the main component, it will combine the above ones while capturing the data and showing the desired behavior. You will have to overwrite the file that is created with the project with the code below.
style.css is responsible for styling the application.
You have to change the fields <YOUR_FIREBASE_PROJECT_NAME> and
<YOUR_WEB_API_KEY> of firebase.jsx. Remember you saved these values at the end of section 2 of this guide.
With that done lets put everything in place. Make sure the NodeMCU board is powered on and has connected to the specified Wi-Fi, then you can open the browser on localhost:3000 assuming you have started the development server already (using npm start).
Moving the distance sensor will send the information to the database and the application will consume this data, automatically changing the value and the size of the blue rectangle on the canvas.
Awesome! You made it to the very end of this tutorial. Thank you very much for your attention and feel free to ask me anything if you have encountered a problem.
If you feel like, follow me on Twitter @pflevy.