Communicating with Edge Devices across Long Distances Using LoRa
local graph
Chapter 12 — Communicating with Edge Devices across Long Distances Using LoRa
Section titled “Chapter 12 — Communicating with Edge Devices across Long Distances Using LoRa”Long Range (LoRa) is a wireless protocol that you can use to receive and send data over long distances using low-powered devices. You can use these edge devices with solar panels or other sources of energy. Sometimes, your edge devices use batteries and are not connected to a common power source like we often find in our houses. When you are crafting edge systems, you could use edge devices using sensors that you have to configure. You could use prototype hardware platforms such as Arduino or devices such as ESP32 microcontrollers or a Raspberry Pi. These devices support LoRa modules to bring communication capabilities to your device, which is crucial for sending and receiving data from devices. In this chapter, we are going to explore how to take advantage of the LoRa wireless protocol to send or receive data from long distances. We will continue expanding the options for monitoring edge devices as in the previous chapter but now using the LoRa wireless protocol.
In this chapter, we’re going to cover the following main topics:
- LoRa wireless protocol and edge computing
- Deploying MySQL to store sensor data
- Deploying a service to store sensor data in a MySQL database
- Programming the ESP32 microcontroller to send sensor data
- Programming the ESP32 microcontroller to receive sensor data
- Visualizing data from ESP32 microcontrollers using MySQL and Grafana
Technical requirements
Section titled “Technical requirements”To deploy our databases in this chapter, you will need the following:
- A single or multi-node K3s cluster that can use ARM devices with MetalLB and Longhorn storage installed. This example will be tested using a Raspberry Pi 4B with 4 GB of RAM and using Ubuntu 20.04 or later for ARM 64-bit.
- A Kubernetes cluster hosted in your public cloud provider (AWS, Azure, GCP) or your private cloud.
- 2 ESP32 microcontrollers with the LoRa module installed. We are using the Heltec ESP32 + Lora v2 model; one to send and the other to receive data.
- Arduino IDE installed on your Mac. You can use Windows since it’s pretty similar to configure, and it is also more stable when working with hardware.
- A USB 2.0 A-Male to Micro B cable for programming your ESP32 devices.
- A Keyes DHT11 sensor or similar connected to your edge device to read temperature and humidity.
kubectlconfigured to be used in your local machine for your Kubernetes cloud cluster or your K3s cluster to avoid using the--kubeconfigparameter.- Clone the GitHub repository at https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/tree/main/ch12 if you want to run the YAML configurations using
kubectl applyinstead of copying the code from this book. Take a look at thecodedirectory for Arduino source codes for Heltec devices and theyamldirectory for YAML configurations. These are located inside thech12directory.
Now, let’s understand how our scenario of using LoRa devices, Prometheus, and Grafana is going to work.
LoRa wireless protocol and edge computing
Section titled “LoRa wireless protocol and edge computing”LoRa refers to a radio modulation technique for long distances, and together with LoRaWAN, it defines a network protocol that can be used to interconnect devices. LoRaWAN is also a network architecture that uses a start-of-start topology in which the gateway relays messages between edge devices. LoRa uses three popular frequencies: 433, 868, and 915. 433 is sometimes used outdoors. 868 is used in Europe and 915 is used in America. LoRaWAN has gateway devices that can connect LoRa networks to the internet. LoRa is designed for low power, which is why LoRa is used for applications in IoT to interconnect devices across long distances.
As we know, the goal of edge computing is to process data near the source. Therefore, LoRa allows us to implement edge computing and interconnect devices for long distances without using a lot of energy. Some use cases include agriculture, buildings, supply chain, logistics, geo localization applications, and more. Some common devices that support LoRa are Heltec ESP32 devices, which are designed for low power consumption. We are going to focus on configuring a Heltec ESP32 device with LoRa support in this chapter.
To start our use case implementation of using LoRa on the tiny edge to interact with a far edge Kubernetes cluster, let’s explore the following diagram:

Figure 12.1 – Monitoring with ESP32 devices and LoRaWAN
This diagram is divided into different layers. You can see how the data flows between the far edge, where LoRa communication is implemented, to the cloud layer. But first, let’s describe the different components of this use case that we want to implement:
- Tiny edge: In this layer, we are going to find the Heltec ESP32 devices, which you can classify as devices that send or receive data. This device sends data, reads data from the DHT11 sensor, and sends the information in JSON format using the LoRa protocol. The other devices read the information, send it across LoRa, and send it to the cluster on the far edge using a post request in a LAN. You can add as many devices to send data as you want.
- Far edge: Here, you can find a single or multi-node K3s cluster using ARM devices. This cluster provides the metrics service, which receives data in JSON format from the tiny edge. Once the data is received, the metrics service writes this data to the cloud layer in the MySQL deployment inside a Kubernetes cluster provisioned in the cloud provider. This could be Amazon, GCP, Azure, and so on.
- Near edge: This layer contains the local router that connects the local network to the internet. Keep in mind that the cluster in the far edge works as a gateway to send data from the LoRa network to the internet.
- Cloud layer: Here, you can find the Kubernetes cluster, which contains MySQL and Grafana. MySQL stores data coming from your local sensors, while Grafana uses MySQL to create dashboards using your sensor data.
In summary, all your sensor data is coming from ESP32 devices, some equipped with sensors. These devices send and receive data using the LoRa protocol. When a receiver device receives information, it’s transformed into JSON format and then sent to a Kubernetes service located on the far edge. After this service receives this information, it’s forwarded to the cloud layer and stored in a MySQL database. MySQL is used by Grafana to show sensor data collected at the edge in real time. Now, let’s deploy our MySQL databases to store data.
Deploying MySQL to store sensor data
Section titled “Deploying MySQL to store sensor data”Before you can store data from your devices using LoRa, you must deploy your database. For this, we are going to use MySQL. MySQL is a pretty popular database that you can use to store data from your sensor. The main advantage of using MySQL is that it is well documented, and you can find a lot of examples on the internet. For our deployment, we are going to use a PersistentVolumeClaim and the mysql:8.0.28-oracle image. Even if you decide to deploy your MySQL over the cloud or locally at the edge, you must use a LoadBalancer service so that you have an endpoint for the service that is going to store all sensor data. Our MySQL database will be deployed in the default namespace to simplify the implementation. To deploy our MySQL database, follow these steps:
- Create a
PersistentVolumeClaimwith 5 GB of storage:$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: PersistentVolumeClaimmetadata:name: db-pv-claimspec:accessModes:- ReadWriteOnceresources:requests:storage: 5GiEOF
Important Note
Don’t forget to use ConfigMaps and Secrets for a more secure and advanced configuration. You can explore Chapter 10, SQL and NoSQL Databases at the Edge, for more details.
- Now, let’s deploy our MySQL database. Our deployment is going to use the previous
PersistentVolumeClaim, calleddb-pv-claim, for this run:$ cat <<EOF | kubectl apply -f -apiVersion: apps/v1kind: Deploymentmetadata:name: mysqlspec:selector:matchLabels:app: mysqlstrategy:type: Recreatetemplate:metadata:labels:app: mysqlspec:containers:- image: mysql:8.0.28-oraclename: mysqlenv:- name: MYSQL_DATABASEvalue: sensor_data- name: MYSQL_USERvalue: lora_mysql- name: MYSQL_PASSWORDvalue: lora123-- name: MYSQL_ROOT_PASSWORDvalue: lora123-ports:- containerPort: 3306name: mysqlvolumeMounts:- name: mysql-persistent-storagemountPath: /var/lib/mysqlvolumes:- name: mysql-persistent-storagepersistentVolumeClaim:claimName: db-pv-claimEOF
In this deployment, we are using some environment variables:
MYSQL_DATABASE: Creates an initial databaseMYSQL_USER: Creates a super admin user for the database defined inMYSQL_DATABASEMYSQL_PASSWORD: Sets a password for the defined user in theMYSQL_USERvariableMYSQL_ROOT_PASSWORD: Sets a password for the root user
Important Note
If you are using a multi-node cluster, use the nodeSelector option to prevent issues with the provisioned PersistentVolumeClaim.
- Now, we need a
ClusterIPservice. This will be used inside Grafana to configure this MySQL database as a data source:$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: Servicemetadata:creationTimestamp: nullname: mysqlspec:ports:- port: 3306protocol: TCPtargetPort: 3306selector:app: mysqltype: ClusterIPstatus:loadBalancer: {}EOF - We also need a
LoadBalancerservice to expose MySQL. This service will be used to expose MySQL to the outside world. This could be over the internet or using an IP address inside your local network. Regardless, the provisioned load balancer IP address will be used inside your ESP32 devices. These ESP32 devices are going to send information to this endpoint, using our metrics service to finally store sensor data in MySQL. Let’s create thisLoadBalancerservice:$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: Servicemetadata:creationTimestamp: nullname: mysql-lbspec:ports:- port: 3306protocol: TCPtargetPort: 3306selector:app: mysqltype: LoadBalancerstatus:loadBalancer: {}EOF
Now that MySQL is running, we have to create a table to store sensor data. To do so, follow these steps:
- Create a MySQL CLI client to run some commands to create the table where data will be stored:
$ kubectl run client -it --rm --image=mysql:8.0.28-oracle -- bash
Once you are inside, run the following command. This will ask you for a password. Use lora123- as your password:
$ mysql -u lora_mysql -h mysql -pThe prompt will change to something similar to mysql>.
- Create the metric table and include the
device,temperature_c,temperature_f,humidity, andtimefields:use sensor_data;CREATE TABLE metric (device INT NOT NULL,temperature_c DECIMAL(4,2),temperature_f DECIMAL(4,2) NOT NULL,humidity DECIMAL(4,2) NOT NULL, time DATETIME NOT NULL);
First, we must select the sensor_data database to create the table inside using the use command. Then, we must create the table metric using the CREATE TABLE command. We configure it so that each field has to have values. We use DECIMAL(4,2), which means 4-2 = 2 integer numbers and 2 decimals. We store data using the format used by the now() MySQL function as MONTH/DAY/YEAR HOUR:MINUTE:SECOND.
Here is a small explanation of what each field contains:
device: This represents the number of the ESP32 Lora device that sends sensor data. This could be a number greater than 0.temperature_c: This is the temperature measured in Celsius.temperature_f: This is the temperature measured in Fahrenheit.humidity: Ambient humidity, measured as a percentage.
- Exit the MySQL client using the
quitcommand inside MySQL. - Exit the client using the
exitcommand. After exiting, the pod will be deleted. - Get the MySQL IP address provisioned in the
LoadBalancerservice. To do so, run the following commands:$ MYSQL_IP="$(kubectl get svc mysql-lb -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')"$ echo $MYSQL_IP
The echo command is going to show the IP address of your MySQL.
Now that our MySQL database has been deployed and is ready to be used, let’s deploy our metrics application on the far edge to store data in this MySQL database.
Deploying a service to store sensor data in a MySQL database
Section titled “Deploying a service to store sensor data in a MySQL database”For this scenario, we need to deploy a service to store data in the previously deployed MySQL. We are going to call this metrics. The metrics service contains the following code:
from flask import Flask, requestimport mysql.connectorimport os
app = Flask(__name__)
@app.route('/')def hello_world(): return 'It works'
def insert(data): conn = mysql.connector.connect( host=os.environ['HOST'], user=os.environ['MYSQL_USER'], password=os.environ['MYSQL_PASSWORD'], database=os.environ['MYSQL_DATABASE'] ) cursor = conn.cursor() sql = "INSERT INTO metric "+\ "(device,temperature_c,"+\ "temperature_f,humidity,time) "+\ "VALUES (%s,%s,%s,%s,now());" val = (data["d"],data["t"],data["t_f"],data["h"]) cursor.execute(sql,val) conn.commit() cursor.close() conn.close()
@app.route('/device',methods = ['POST'])def device(): data = request.json print(data) #Process data in some way t_farenheit = float(data["t"])*(9/5)+32 data["t_f"] = t_farenheit insert(data) return "processed"
if __name__ == '__main__': app.run(host='0.0.0.0', port=3000, debug=True)This code has two endpoints:
/: This is only a test URL./device: This gets data from POST requests and writes it to MySQL by calling theinsertfunction.
It also uses the insert(data) function to insert the data into the MySQL deployed in the cloud layer. This function takes the data coming from LoRaWAN and recalculates the temperature in Fahrenheit. Once stored, the data returns the process word.
This script also uses the following environment variables:
HOST: Defines the IP address where MySQL is listeningMYSQL_USER: The user to connect to the databaseMYSQL_PASSWORD: The password used to connect to the databaseMYSQL_DATABASE: The database name wheremetricsis going to store data
Our deployment in Kubernetes must have these variables set to work properly, without errors.
Important Note
You can check the code on how to build a container based on this example at https://github.com/sergioarmgpl/containers/tree/main/metric.
Now that we’ve looked at the code of the metrics service, let’s deploy metrics to start storing sensor data in this database. For this, follow these steps:
- Deploy our
metricsapplication so that it’s running:$ cat <<EOF | kubectl apply -f -apiVersion: apps/v1kind: Deploymentmetadata:creationTimestamp: nulllabels:app: metricsname: metricsspec:replicas: 1selector:matchLabels:app: metricsstrategy: {}template:metadata:creationTimestamp: nulllabels:app: metricsspec:containers:- image: sergioarmgpl/metricname: metricenv:- name: HOSTvalue: "192.168.0.240"- name: MYSQL_USERvalue: "lora_mysql"- name: MYSQL_PASSWORDvalue: "lora123-"- name: MYSQL_DATABASEvalue: "sensor_data"resources: {}status: {}EOF
In this deployment, we are using the following values for the environment variables:
HOST: This is the IP address of theLoadBalancerservice that was created for our MySQL – that is,192.168.0.240. This will be the IP address that was returned in the last step of the previous section.MYSQL_USER: The MySQL user. In this case, this islora_mysql.MYSQL_PASSWORD: The password forlora_mysql. In this case, this islora123-.MYSQL_DATABASE: The name of the MySQL database where sensor data will be stored. In this case, this issensor_data.
Important Note
You can customize all these values to fit your needs. Remember that you can use ConfigMaps or Secrets to secure your deployments. We are using hard-coded values just to simplify the implementation. Check out Chapter 10, SQL and NoSQL Databases at the Edge, for this kind of configuration.
- Now, let’s create our
LoadBalancerservice for themetricsdeployment. The provisioned IP address will be hard-coded inside the code of our ESP32 devices. To create the service, run the following code:$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: Servicemetadata:creationTimestamp: nullname: metricsspec:ports:- port: 3000protocol: TCPtargetPort: 3000selector:app: metricstype: LoadBalancerstatus:loadBalancer: {}EOF - To obtain the provisioned IP address from the
metricsservice, run the following commands:$ METRICS_IP="$(kubectl get svc metrics -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')"$ echo METRICS_IP
The echo command will show the IP address of our metrics application. Take note of this value since it will be used to program our ESP32 devices. Let’s assume that this value is 192.168.0.241 for this scenario.
Now that we have deployed our metrics service on the far edge, let’s configure our ESP32 devices so that they can send and receive data.
Programming the ESP32 microcontroller to send sensor data
Section titled “Programming the ESP32 microcontroller to send sensor data”ESP32 is a low-cost, low-power microcontroller chip and the successor of the ESP8266 microcontroller. In this chapter, we will be using the Heltec ESP32 + LoRa, which is an ESP32 microcontroller plus the capability to use the LoRa wireless protocol. This microcontroller can also send and receive data using the LoRa wireless protocol using the integrated SX1276 chip in this Heltec dashboard.
Before configuring our device, we have to do the following:
- Connect the DHT11 sensor to the Heltec ESP32 + LoRa device.
- Install the USB to UART bridge driver.
- Install and configure Arduino IDE to program the Heltec ESP32 + LoRa device.
- Flash the Heltec ESP32 + Lora device.
So, let’s get started by connecting a DHT11 sensor to our Heltec ESP32 + Lora device.
Configuring Heltec ESP32 + LoRa to read DHT11 sensor data
Section titled “Configuring Heltec ESP32 + LoRa to read DHT11 sensor data”Heltec devices are often used for IoT, and ESP32 is a very popular device for IoT and LoRa implementations. You can find the official documentation for Heltec devices at https://heltec-automation-docs.readthedocs.io/en/latest. For our LoRa implementation, we are going to use the following diagram:

Figure 12.2 – Heltec ESP32 reading data from the DHT11 schema
To connect your Heltec ESP32 to your DHT11 sensor, follow these steps. This is the sender device:
- Connect your LoRa antenna. This could affect the transmission range if the antenna is not connected.
- Connect your power source to the USB connection. You must use a USB 2.0 A-Male to Micro B cable.
- Connect your
PIN 17with a wire to theSinput in the DHT11 sensor. - Connect the GND (ground) to the
Ginput in the DHT11 sensor. - Connect one of the 3V3 volt outputs to the
Vinput in the DHT11 sensor.
For your receiver device, just follow these steps:
- Connect your LoRa antenna.
- Connect your power source to the USB connection as your sender device.
Important Note
Remember that you have to use a power source supply or a battery that gives you 3.5 or 5 volts. To learn more, check out https://heltec-automation-docs.readthedocs.io/en/latest/esp32/index.html.
With that, your sender and receiver devices are ready to upload some code. Now, let’s install all the software that we need to upload some code into our devices.
Installing the USB to UART bridge driver
Section titled “Installing the USB to UART bridge driver”When installing the generic SiLabs CP210X driver that installs support for the USB to UART bridge, this driver is going to recognize your device on your computer. In this way, your Heltec device can connect to the computer and interact with Arduino IDE using serial communication.
To install this driver, you can visit the following link for detailed instructions: https://heltec-automation-docs.readthedocs.io/en/latest/general/establish_serial_connection.html. There, you can find the latest documentation to install the driver on Windows and Mac.
These instructions consist of downloading various drivers:
- For Windows: https://www.silabs.com/documents/public/software/CP210x_Windows_Drivers.zip
- For Mac: https://www.silabs.com/documents/public/software/Mac_OSX_VCP_Driver.zip
You must follow the wizard to install them, depending on your system. Once you have installed the driver, you can connect your device to your system and check if it was detected. For Mac, you can execute the following command:
$ ls /dev | grep cu | grep 'usbserial\|UART'You will see an output similar to the following:
cu.SLAB_USBtoUARTcu.usbserial-0001This means that your device was detected. Some common problems may occur where your device can’t be recognized. This will be because of the cable that you are using; try to find a cable in an optimal condition for your computer to detect the device.
For Windows, you will see that your device appears in the Hardware manager in the part of ports. Then, the device will appear like so:
- Silicon Labs CP210X USB to UART bridge (COM3)
This means that your Heltec device was detected successfully.
Now that your system recognizes the device, it’s time to install Arduino IDE to upload some code inside your Heltec device.
Installing Arduino IDE
Section titled “Installing Arduino IDE”Arduino IDE is a piece of software that you can use to upload code to your boards. In this case, we are using a board designed by Heltec, which is the one we called the Heltec device. To start using Arduino IDE, follow these steps:
- Download Arduino IDE by going to https://www.arduino.cc/en/software. This will depend on which operating system are you using. You can choose between Windows, Linux, or Mac. In this chapter, we are going to cover just Mac. We will use Arduino 1.8.19.
Important Note
You can also follow the official page of Heltec, which explains how to install the Heltec driver and Arduino IDE for Windows and Mac. The quick start link is https://heltec-automation-docs.readthedocs.io/en/latest/esp32/quick_start.html.
- Open Arduino IDE by clicking on its icon on your desktop or inside Launchpad on Mac.
- Click File | Preferences and paste https://github.com/Heltec-Aaron-Lee/WiFi_Kit_series/releases/download/0.0.5/package_heltec_esp32_index.json inside the Additional Boards Manager URLs field. Then, click OK. The new ESP32 board will be loaded in Arduino IDE:

Figure 12.3 – Configuring Preferences to use the Heltec ESP32 device
- Now, go to Tools | Board | Boards Manager:

Figure 12.4 – The Boards Manager menu
- Search for
heltecin the new pop-up dialog, then click Install to install it:
Figure 12.5 – Searching for heltec on Boards Manager
You will see something similar to the following:

Figure 12.6 – Heltec board installed via Boards Manager
- Now, select the board by going to Tools | Board | Heltec ESP32 Arduino and select WiFi LoRa 32(V2):

Figure 12.7 – Setting WiFi LoRa 32(V2) as the default board
- Now, repeat this process by going to Tools | Manage Libraries, searching for the DHT sensor library from Adafruit, and choosing Heltec ESP32 Dev-Boards. Make sure you install it.
With that, our Arduino IDE is ready to be used. Now, let’s learn about some configurations that you will need in case of errors.
Troubleshooting Arduino IDE when using Heltec ESP32 + LoRa
Section titled “Troubleshooting Arduino IDE when using Heltec ESP32 + LoRa”macOS has some challenges, depending on your Mac version, but you can fix them.
One is the esptool Python library. To fix it, follow these steps:
- Copy your current
esptool.pyfile inside thetoolsfolder. The command will look as follows:$ cp /Users/<YOUR_USER>/Library/Arduino15/packages/Heltec-esp32/hardware/esp32/<X.X.X> /tools/esptool.py /Users/ <YOUR_USER> /Library/Arduino15/packages/Heltec-esp32/tools/esptool_py/<X.X.X>/ - Change the permissions for the
esptool.pyfile:$ chmod +x esptool.py
Run the esptool.py file:
$ ./esptool.py- Sometimes, you have to install the serial library if the previous command returns an error. For this, you have several options. One is to install the library from scratch by going to https://github.com/pyserial/pyserial/releases. In this case, we are using version 3.4. For this run, the following commands:
$ wget https://github.com/pyserial/pyserial/archive/refs/tags/v3.4.zip$ sudo python setup.py install
- Then, try again if the
./esptool.pycommand returns errors. - Depending on which Python version is installed on your computer, you can try this other alternative:
$ sudo pip install pyserial or$ sudo pip3 install pyserial
- The last alternative is to use
easy_installto install the pyserial library. To do so, run the following command:$ sudo easy_install pyserial
Important Note
macOS Monterrey deletes Python 2.7 by default, so you have to install this Python version. You could stay with Python 3, but you have to open Arduino IDE with the open /Applications/Arduino.app command. You can find a more detailed way to fix these problems by watching the following video: https://www.youtube.com/watch?v=zkyoghpT8_U.
Another problem to fix, depending on your Arduino version, is that Heltec installs its Wi-Fi library. So, when you try to compile and upload the program, sometimes, you will see some errors. To avoid these errors, you have two options:
- Uninstall the default Arduino Wi-Fi library by going to Tools | Manage libraries. Then, find the Wi-Fi library from Arduino and uninstall it.
- Remove or rename the default Arduino Wi-Fi library folder by using the following commands:
$ cd /Applications/Arduino.app/Contents/Java/libraries$ mv libraries/WiFi
Important Note
On Windows, the installation is smooth, so you won’t have to fix this kind of issue.
Now, it is time to upload some code to your devices using Arduino IDE.
Uploading code to the ESP32 microcontroller to send sensor data
Section titled “Uploading code to the ESP32 microcontroller to send sensor data”Now, let’s upload our code to our Heltec devices. Let’s start with the sender device. This device is going to capture data from the DHT11 sensor and send it to the receiver device using the LoRa wireless protocol. Let’s create a new file by going to File | New. By default, you will see something similar to the following:
void setup() { // put your setup code here, to run once:}
void loop() { // put your main code here, to run repeatedly:}Now, replace it with the following code:
#include "heltec.h"#define BAND 915E6
#include "DHT.h"#define DHTPIN 17#define DHTTYPE DHT11DHT dht(DHTPIN, DHTTYPE);
#define DEVICE 1#define DELAY 3000
void setup(){ Heltec.begin(false,true,true,true,BAND); Serial.begin(9600); LoRa.setSyncWord(0xF3); Serial.println("LoRa started"); dht.begin();}
void sendTH(){ String values = ""; LoRa.beginPacket(); float h = dht.readHumidity(); float t = dht.readTemperature(); if (isnan(h) || isnan(t)) { Serial.println(F("Failed to get data from sensor")); return; } String hS = (String)h; String tS = (String)t; String dS = (String)DEVICE; values = "{\"t\":"+tS+",\"h\":"+hS+",\"d\":"+dS+"}"; Serial.println(values); LoRa.print(values); LoRa.endPacket();}
void loop(){ delay(DELAY); sendTH();}Let’s look at the preceding code in more detail:
heltec.h: We import the library to use the ESP32 + LoRa device. With this, you can use the Wi-Fi and LoRa wireless protocol.DHT.h: We import the library to read data from the DHT11 sensor.BAND: We set the band to use to connect the devices. For Europe, you have to use a value of868E6, while for America, you have to use915E6.DHTPIN: This is a constant value that we use to set the PIN that’s used to read data in our ESP32 device. In this case, we are using pin 17. Keep in mind that the pin to use has to support digital information.DHTTYPE: This defines the type of sensor. The library that we are using supports the DHT11 and DHT12 sensors.DEVICE: This is the device number that is sending data. You must change this value every time you upload the code on a device, just to identify each device using a number.DELAY: This is the time to wait until sending the next sensor measure data.setup(): This function does an initial configuration for the Heltec device and sets the network ID for LoRa using0xF3– that is, the network ID for our devices. This value must be set between0and0xFF.sendTH(): This function captures and sends the sensor data with the LoRa Wi-Fi protocol in the{"t":26.2,"h":35.5,"d":1}format, wheretis the temperature in Celsius,his the humidity in percentages, anddis the device number.loop(): This function runs as a loop and callssendTH()to capture and send sensor data using LoRa.
Important Note
You can find the source code of the sender and receiver device at https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/tree/main/ch12/code/arduino.
In summary, first, we set all the constant values to configure how to read data from the DHT11 sensor and send data using LoRa. Then, the setup is called to prepare reading data from the sensor and the initial configuration for LoRa. Finally, loop() runs as a loop that calls sendTH(), which sends and receives data. Once you have your device with this code, just turn it on to send data. To stop sending data, you must power off the device.
Pay attention to the lines that contain the Serial.println command. This command prints information using the serial port. You can troubleshoot what is happening in your device using Arduino when your device is powered with your USB port from your laptop by opening Tools | Serial Monitor. Doing this will show all the Serial.println outputs inside the window:

Figure 12.8 – Monitoring with Heltec ESP32 devices in Arduino
Important Note
To connect your device to macOS, you need a USB A-to-USB C adaptor. If you need a power source with at least 5 volts, you can also use a battery bank instead of connecting the device to a laptop or a computer.
Now that your Heltec sender device is working, you can start uploading the code for the receiver device.
Programming the ESP32 microcontroller to receive sensor data
Section titled “Programming the ESP32 microcontroller to receive sensor data”Now, we have to configure our Heltec ESP32 device to receive the sensor data and send it to the far edge cluster by doing a request across the wireless network. To start, we must create another file by clicking File | New and replacing the default content with the following code:
#include "heltec.h"#include "WiFi.h"#include <HTTPClient.h>#define BAND 915E6#define METRICS_IP "192.168.0.241"void setup(){ Heltec.begin(false, true, true, true, BAND); Serial.begin(9600); LoRa.setSyncWord(0xF3); Serial.println("LoRa started"); WIFISetUp();}
void WIFISetUp(void){ WiFi.disconnect(true); delay(100); WiFi.mode(WIFI_STA); WiFi.setAutoConnect(true); WiFi.begin("NET_NAME","PASSWORD"); delay(100);
byte count = 0; while(WiFi.status() != WL_CONNECTED && count < 10) { count ++; delay(500); Serial.println("Connecting..."); } if(WiFi.status() == WL_CONNECTED) Serial.println("Connected OK"); else Serial.println("Failed");}void callURL(String data){ String postData = data; Serial.println("Sending: " + postData); WiFiClient client; HTTPClient http; http.begin(client, "http://"+((String)METRICS_IP)+":3000/device"); http.addHeader("Content-Type","application/json"); int httpResponseCode = http.POST(postData); Serial.println("HTTP Response code xyz: "+(String)httpResponseCode); http.end();}
void loop(){ onReceive(LoRa.parsePacket());}
void onReceive(int packetSize){ String incoming = ""; if (packetSize == 0) return;
while (LoRa.available()) incoming += (char)LoRa.read();
Serial.println("Received: " + incoming); callURL(incoming);}Let’s understand the code a little bit:
Heltec.h,WiFi.h,HTTPClient.h: These are the libraries that we are using for the receiver.Heltec.his used to send data with LoRa,WiFi.his the Wi-Fi Heltec library to connect to the wireless network, andHTTPClient.his used to send a request to our far edge server with the sensor data.BAND: Here, we set the same band that’s used in the sender device.METRICS_IP: This is the IP address of themetricsservice in your cluster. To get this value, go to the Deploying a service to store sensor data in a MySQL database section. Replace this value before uploading the code to your device.setup(): Here, we configure the Heltec device to receive data from the same LoRa network defined bysetSyncWord. It also configures the Wi-Fi connection.WIFISetUp(void): Here, we configure the Wi-Fi connection. To do so, you must replaceNET_NAMEwith your network name andPASSWORDwith the necessary password to access your connection.callURL(String data): This calls themetricsservice in your cluster. The URL to access it will be something likehttp://METRICS_IP:3000/device, but this function automatically generates this URL using the value of theMETRICS_IPconstant.onReceive(int packetSize): This receives information that’s been sent to the configured network using the LoRa protocol and then sends that information to themetricsservice in the far edge cluster using an HTTP POST request.loop(): This function runs as a loop and callsonReceive(int packetSize), which gets LoRa packets that contains sensor data. Then, it sends these to themetricsendpoint in the far edge cluster.
To summarize, first, we configure the device so that we can connect to the same LoRa network. We must also configure the Wi-Fi, which has access to the far edge server. loop() constantly checks if it has received some data to send it to the metrics server in the far edge cluster.
Now, upload the code to your device and turn it on, as we did in the Programming the ESP32 microcontroller to send sensor data section. With that, our devices have been configured, so let’s move to the last step and configure Grafana to show all our data in a dashboard, using the sensor data stored in MySQL.
Visualizing data from ESP32 microcontrollers using MySQL and Grafana
Section titled “Visualizing data from ESP32 microcontrollers using MySQL and Grafana”Now, let’s finish off our implementation of a real-time temperature and humidity system. For this, we are going to use Grafana to create our reports and MySQL as our source of data to feed the reports. You can deploy this software in Kubernetes in the cloud or a private cloud using a network that can be accessed by your edge clusters. In this section, we are assuming that we are using Kubernetes in the cloud. To start creating our reports, follow these steps:
- Create the necessary namespace monitoring:
$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: Namespacemetadata:creationTimestamp: nullname: monitoringspec: {}status: {}EOF
- Create a ConfigMap to create a default data source that contains our MySQL connection:
$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: ConfigMapmetadata:name: grafana-datasourcesnamespace: monitoringlabels:grafana_datasource: "true"data:datasource.yaml: |-apiVersion: 1datasources:- name: sensor_datatype: mysqlurl: mysql.default.svcaccess: proxydatabase: sensor_datauser: lora_mysqlsecureJsonData:password: lora123-isDefault: trueEOF
This will be the default data source configured in your grafana deployment.
Important Note
You can use a Secret object to secure sensitive data, but we are using ConfigMap to simplify this example.
- Deploy Grafana so that it can use the previous ConfigMap by running the following code:
$ cat <<EOF | kubectl apply -f -apiVersion: apps/v1kind: Deploymentmetadata:name: grafananamespace: monitoringspec:replicas: 1selector:matchLabels:app: grafanatemplate:metadata:name: grafanalabels:app: grafanaspec:containers:- name: grafanaimage: grafana/grafana:8.4.4ports:- name: grafanacontainerPort: 3000resources:limits:memory: "1Gi"cpu: "1000m"requests:memory: 500Mcpu: "500m"volumeMounts:- mountPath: /var/lib/grafananame: grafana-storage- mountPath: /etc/grafana/provisioning/datasourcesname: grafana-datasourcesreadOnly: falsevolumes:- name: grafana-storageemptyDir: {}- name: grafana-datasourcesconfigMap:defaultMode: 420name: grafana-datasourcesEOF
- Let’s create the service to access Grafana:
$ cat <<EOF | kubectl apply -f -apiVersion: v1kind: Servicemetadata:creationTimestamp: nulllabels:app: grafananame: grafananamespace: monitoringspec:ports:- port: 3000protocol: TCPtargetPort: 3000selector:app: grafanatype: ClusterIPEOF
- Use
port-forwardto forward the previous Grafana service. This will help us connect to Grafana locally:$ kubectl port-forward svc/grafana 3000 -n monitoring --address 0.0.0.0 - Go to
http://localhost:3000. When the login page appears, use the usernameadminand passwordadminand click on the Log in button. After that, you will be you for new credentials:
Figure 12.9 – Grafana login
- After logging in, you can check that your default data source is set to MySQL by going to Configuration | Data sources:

Figure 12.10 – Grafana configuration menu
You will see something similar to the following:

Figure 12.11 – sensor_data default data source
- Now, click on Create | Dashboard:

Figure 12.12 – Creating a dashboard
Then, click Add a new panel:

Figure 12.13 – Grafana – The Add panel page
- Then, configure the new dashboard with the following query and values:
SELECTUNIX_TIMESTAMP(time) AS "time",temperature_c AS "Temperature(Celcius)",temperature_f AS "Temperature(Farenheit)",humidity AS "Humidity(%)"FROM metricWHERE$__timeFilter(time)and device=1ORDER BY time
You must edit the default query by clicking on the pencil icon. Then, copy the previous query there:
Figure 12.14 – Editing the default MySQL query
We have set Title to Device 1 Sensor Data here. The new dashboard will look like this:

Figure 12.15 – The New dashboard/Edit Panel window
After changing the query if data is available, you will see a graph with three lines – one representing the temperature in Celsius, another representing the temperature in Fahrenheit, and the humidity as a percentage. Remember to set the dashboard to visualize the proper range of data – for example, to show data from the last 5 minutes – and refresh the dashboard every 5 seconds.
- After that, save your dashboard by clicking on the Save button.
Important Note
Check out Chapter 11, Monitoring the Edge with Prometheus and Grafana, for more details about customizing your dashboard.
- Finally, your dashboard will look as follows:

Figure 12.16 – ESP32 monitoring dashboard in Grafana
At this point, you are visualizing the data from your Heltec devices to send and receive data. This device interacts with your far edge cluster. If you chose to deploy Grafana and MySQL on the cloud, this scenario is also interacting with the cloud layer. All these components interact with each other to do their job. Remember that this is a simple implementation that you can extend to your own. Now, let’s summarize what we have learned in this chapter.
Summary
Section titled “Summary”In this chapter, we explored how to implement an edge computing system by using LoRa devices to send and receive sensor data. Finally, we implemented a dashboard using MySQL and Grafana. In this way, the LoRa wireless protocol represents a way to implement lower-cost systems that need to transmit information close to the edge. Therefore, LoRa is a common choice as a transmission protocol for edge devices and IoT applications. In the next chapter, we are going to use a GPS module to extend the range of communication and databases to implement geolocation applications.
Questions
Section titled “Questions”Here are a few questions to validate your new knowledge:
- What are the uses and advantages of using the LoRa wireless protocol?
- What is LoRaWAN?
- How can I use a Heltec ESP32 + LoRa device to send sensor data?
- How can I use Arduino IDE to program ESP32 devices?
- How can I create a simple gateway to send data coming from LoRaWAN to LAN?
- How can I use MySQL and Grafana to create reports?
Further reading
Section titled “Further reading”Please refer to the following references for more information on the topics covered in this chapter:
- What is the LoRaWAN specification?: https://lora-alliance.org/about-lorawan
- What is LoRa?: https://www.semtech.com/lora/what-is-lora
- LoRa applications: https://www.semtech.com/lora/lora-applications
- LoRaWAN Frequency Plans: https://www.thethingsnetwork.org/docs/lorawan/frequency-plans.
- CP210x USB to UART Bridge VCP Drivers: https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers
- Arduino download software: https://www.arduino.cc/en/software
- HttpClient documentation and examples: https://github.com/amcewen/HttpClient
- All fixes to run ESP32/Arduino on Arduino IDE and Platform I/O using MacOS Big Sur and Newer: https://www.youtube.com/watch?v=zkyoghpT8_U
- ESP32 + LoRa Heltec documentation: https://heltec-automation-docs.readthedocs.io/en/latest/esp32/index.html
- Heltec Automation Docs Page: https://heltec-automation-docs.readthedocs.io/en/latest
- Heltec ESP32 LoRaWAN library and examples: https://github.com/HelTecAutomation/ESP32_LoRaWAN
- WIFI LoRa 32(V2) Pinout Diagram: http://resource.heltec.cn/download/WiFi_LoRa_32/WIFI_LoRa_32_V2.pdf
- Provisioning Grafana: https://github.com/grafana/grafana/blob/main/docs/sources/administration/provisioning/index.md