Skip to content

Commit 5bee290

Browse files
emqx-ci-robotSwilder-M
authored andcommitted
sync blog
1 parent 1fedc0b commit 5bee290

7 files changed

+737
-234
lines changed

README-JA.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ The world's most scalable and reliable MQTT messaging platform to connect, move
133133
## [Internet of Vehicles | Connected Cars](https://www.emqx.com/ja/blog/category/internet-of-vehicles)
134134
Build a reliable, efficient and industry-specific Internet of Vehicles platform based on EMQ's practical experience, from theoretical knowledge such as protocol selection to practical operations like platform architecture design.
135135

136+
- [DDS:基本、限界、およびMQTT連携について](https://www.emqx.com/ja/blog/navigating-dds-basics-limitations-and-integration-with-mqtt) ([Edit](https://github.com/emqx/blog/blob/main/ja/202408/navigating-dds-basics-limitations-and-integration-with-mqtt.md))
136137
- [車両通信 + UNS:SDVライフサイクル全体のデータ相互運用の実現](https://www.emqx.com/ja/blog/vehicle-and-uns) ([Edit](https://github.com/emqx/blog/blob/main/ja/202408/vehicle-and-uns.md))
137138
- [スマートモビリティの発展:機会と課題](https://www.emqx.com/ja/blog/the-road-to-smart-mobility) ([Edit](https://github.com/emqx/blog/blob/main/ja/202404/the-road-to-smart-mobility.md))
138139
- [V2Xとは?未来に車両とエブリの接続です](https://www.emqx.com/ja/blog/what-is-v2x-and-the-future-of-vehicle-to-everything-connectivity) ([Edit](https://github.com/emqx/blog/blob/main/ja/202310/what-is-v2x-and-the-future-of-vehicle-to-everything-connectivity.md))

README-ZH.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ Explore more with & via EMQ.
191191
## [EMQX Open Source | Broker](https://www.emqx.com/zh/blog/category/emqx)
192192
EMQX is the world's most scalable open-source MQTT broker with a high performance that connects 100M+ IoT devices in 1 cluster, while maintaining 1M message per second throughput and sub-millisecond latency.
193193

194+
- [如何使用 EMQX 接入 CoAP 协议设备](https://www.emqx.com/zh/blog/connecting-coap-devices-to-emqx) ([Edit](https://github.com/emqx/blog/blob/main/zh/202408/connecting-coap-devices-to-emqx.md))
194195
- [使用 EMQX 接入 OCPP 设备:构建新能源车充电网络](https://www.emqx.com/zh/blog/emq-occp-new-energy-charging) ([Edit](https://github.com/emqx/blog/blob/main/zh/202408/emq-occp-new-energy-charging.md))
195196
- [EMQX 跨域集群:增强可扩展性,打破地域限制](https://www.emqx.com/zh/blog/exploring-geo-distribution-in-emqx-for-enhanced-scalability) ([Edit](https://github.com/emqx/blog/blob/main/zh/202407/exploring-geo-distribution-in-emqx-for-enhanced-scalability.md))
196197
- [使用 NGINX 反向代理 EMQX 时获取客户端真实 IP](https://www.emqx.com/zh/blog/getting-the-clients-real-ip-when-using-the-nginx-reverse-proxy-emqx) ([Edit](https://github.com/emqx/blog/blob/main/zh/202407/getting-the-clients-real-ip-when-using-the-nginx-reverse-proxy-emqx.md))
@@ -256,7 +257,6 @@ EMQX is the world's most scalable open-source MQTT broker with a high performanc
256257
- [EMQX Newsletter 2022-04|v5.0 交互优化、云服务新增 5 项功能更新…](https://www.emqx.com/zh/blog/emqx-newsletter-202204) ([Edit](https://github.com/emqx/blog/blob/main/zh/202205/emqx-newsletter-202204.md))
257258
- [EMQX 多版本发布:规则引擎支持重置运行数据、新增连接确认与鉴权完成事件](https://www.emqx.com/zh/blog/emqx-multi-release-rules-engine-supports-reset-run-data) ([Edit](https://github.com/emqx/blog/blob/main/zh/202204/emqx-multi-release-rules-engine-supports-reset-run-data.md))
258259
- [EMQX Newsletter 2022-03|v5.0 功能基本完备、更方便的数据集成、安全轻松部署 EMQX 集群…](https://www.emqx.com/zh/blog/emqx-newsletter-202203) ([Edit](https://github.com/emqx/blog/blob/main/zh/202204/emqx-newsletter-202203.md))
259-
- [一文解决 CoAP 协议设备与外部网络沟通难题](https://www.emqx.com/zh/blog/connecting-coap-devices-to-emqx) ([Edit](https://github.com/emqx/blog/blob/main/zh/202203/connecting-coap-devices-to-emqx.md))
260260
- [EMQX Newsletter 2022-02|开源版 v4.4.0 发布、云服务上线增值功能](https://www.emqx.com/zh/blog/emqx-newsletter-202202) ([Edit](https://github.com/emqx/blog/blob/main/zh/202202/emqx-newsletter-202202.md))
261261
- [EMQX Newsletter 2022-01|v5.0 全新 Dashboard、云服务认证与告警模式增加](https://www.emqx.com/zh/blog/emqx-newsletter-202201) ([Edit](https://github.com/emqx/blog/blob/main/zh/202201/emqx-newsletter-202201.md))
262262
- [EMQX + IoTDB:存储 MQTT 消息到时序数据库](https://www.emqx.com/zh/blog/store-mqtt-messages-to-time-series-database-iotdb) ([Edit](https://github.com/emqx/blog/blob/main/zh/202201/store-mqtt-messages-to-time-series-database-iotdb.md))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ Get to know the preferred protocol in IoT from beginner to master.
111111
## [MQTT Programming](https://www.emqx.com/en/blog/category/mqtt-programming)
112112
Best practice of MQTT in various clients.
113113

114+
- [A Guide on Collecting and Reporting Soil Moisture with ESP32 and Sensor through MQTT](https://www.emqx.com/en/blog/hands-on-guide-on-esp32) ([Edit](https://github.com/emqx/blog/blob/main/en/202408/hands-on-guide-on-esp32.md))
114115
- [Using MQTT on ESP8266: A Quick Start Guide](https://www.emqx.com/en/blog/esp8266-connects-to-the-public-mqtt-broker) ([Edit](https://github.com/emqx/blog/blob/main/en/202405/esp8266-connects-to-the-public-mqtt-broker.md))
115116
- [How to Use MQTT in the Flutter Project](https://www.emqx.com/en/blog/using-mqtt-in-flutter) ([Edit](https://github.com/emqx/blog/blob/main/en/202405/using-mqtt-in-flutter.md))
116117
- [How to Use MQTT in Rust with Rumqttc Client](https://www.emqx.com/en/blog/how-to-use-mqtt-in-rust) ([Edit](https://github.com/emqx/blog/blob/main/en/202404/how-to-use-mqtt-in-rust.md))

en/202408/hands-on-guide-on-esp32.md

Lines changed: 326 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,326 @@
1+
## Introduction
2+
3+
The ESP32 is a powerful Wi-Fi and Bluetooth module that offers a highly integrated SoC solution. Its low power consumption, compact design, and high stability make it ideal for IoT applications. The ESP32 features comprehensive Wi-Fi and Bluetooth network capabilities, allowing it to function as a standalone application or as a slave device to a host MCU.
4+
5+
The [MQTT protocol](https://www.emqx.com/en/blog/the-easiest-guide-to-getting-started-with-mqtt) is a message transport protocol based on a publish/subscribe model. In MQTT, there are two roles: publishers and subscribers. Publishers send messages to a topic, and subscribers subscribe to a topic. When a publisher sends a message to that topic, the subscribers receive the message.
6+
7+
In this tutorial, we will explore how to use the ESP32 and the MQTT protocol to collect and report soil moisture data. We will use the ESP32 as a publisher to send soil moisture data to a topic, allowing a subscriber to receive and monitor this data remotely.
8+
9+
## Project Initialization
10+
11+
Before starting the project, ensure you have the following hardware and software.
12+
13+
### **Hardware Preparations**
14+
15+
1. ESP32 development board
16+
2. Capacitive Soil Moisture Sensor v1.2
17+
18+
**Sensor Overview**
19+
20+
The capacitive soil moisture sensor v1.2 uses voltage to detect soil moisture levels. The sensor readings vary based on the supply voltage and the specific sensor. By placing the sensor in air and water, we can obtain calibration values that help determine whether the soil is dry or wet. For example, some capacitive sensors provide the following readings:
21+
22+
At 1.3V:
23+
24+
- In air: above 2000
25+
- In water: below 1000
26+
27+
At 5V:
28+
29+
- In air: above 800
30+
- In water: below 500
31+
32+
### **Software Preparations**
33+
34+
1. **Arduino IDE**: For writing and uploading code to the ESP32
35+
2. [**MQTTX Client**](https://mqttx.app/) **or another MQTT client**: For testing MQTT message publishing and subscribing
36+
3. **[Free Public MQTT broker](https://www.emqx.com/en/mqtt/public-mqtt5-broker) provided by EMQX**: Supports nearby sensor access and unified management. EMQX Public Broker server access information:
37+
- Broker: `broker.emqx.io`
38+
- TCP Port: `1883`
39+
- TLS Port: `8883`
40+
- Websocket Port: `8083`
41+
- Websockets Port: `8084`
42+
43+
### Hardware Connection
44+
45+
Connect the ESP32 and the soil moisture sensor as follows:
46+
47+
- Sensor VCC to ESP32 VIN
48+
- Sensor GND to ESP32 GND
49+
- Sensor AOUT to ESP32 GPIO36 (ADC0): In this project, we will use the ESP32 pin GPIO36 (ADC0) to connect to the AOUT pin of the moisture sensor to read soil moisture data.
50+
51+
## Connecting ESP32 to the MQTT Broker
52+
53+
### Installing ESP32 Board Support
54+
55+
Open Arduino IDE, go to **File** -> **Preferences**. In the "Additional Boards Manager URLs" field, add the following URL:
56+
57+
```
58+
https://dl.espressif.com/dl/package_esp32_index.json
59+
```
60+
61+
Next, go to **Tools** -> **Board** -> **Boards Manager**, search for ESP32, and install it.
62+
63+
### Installing PubSubClient Library
64+
65+
In Arduino IDE, go to **Sketch** -> **Include Library** -> **Manage Libraries**, search for `PubSubClient`, and install it.
66+
67+
### Initializing WiFi and MQTT Clients
68+
69+
To begin, we need to initialize the WiFi and [MQTT clients](https://www.emqx.com/en/blog/mqtt-client-tools). This will allow the ESP32 to connect to the internet and communicate with the MQTT server. First, include the necessary libraries and define the WiFi credentials:
70+
71+
```c
72+
#include <WiFi.h>
73+
#include <PubSubClient.h>
74+
#include <WiFiClientSecure.h>
75+
#include <ArduinoJson.h>
76+
77+
// WiFi credentials
78+
const char *ssid = "WIFI_SSID"; // Replace with your WiFi name
79+
const char *password = "WIFI_PASSWORD"; // Replace with your WiFi password
80+
81+
// MQTT Broker configuration
82+
const char *mqtt_broker = "broker.emqx.io";
83+
const char *mqtt_topic = "emqx/esp32/moisture";
84+
const char *mqtt_username = "emqx";
85+
const char *mqtt_password = "public";
86+
const int mqtt_port = 8883;
87+
```
88+
89+
Next, initialize the WiFi and MQTT clients:
90+
91+
```c
92+
WiFiClientSecure esp_client;
93+
PubSubClient mqtt_client(esp_client);
94+
```
95+
96+
### Defining the Sensor Pin
97+
98+
The GPIO36 (ADC0) pin on the ESP32 is used to connect to the AOUT pin of the soil moisture sensor. This pin is chosen because it supports analog-to-digital conversion, which is necessary for reading the sensor's analog output.
99+
100+
```c
101+
#define sensorPIN 36
102+
```
103+
104+
### Loading the CA Certificate
105+
106+
To establish a secure connection to the [MQTT broker](https://www.emqx.com/en/blog/the-ultimate-guide-to-mqtt-broker-comparison) using TLS, we need to load a root CA certificate. This example uses the DigiCert Global Root G2 certificate, which is used by the EMQX public broker. If you are using a different server, replace this certificate with the appropriate one.
107+
108+
```c
109+
const char *ca_cert = R"EOF(
110+
-----BEGIN CERTIFICATE-----
111+
MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh
112+
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
113+
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH
114+
MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT
115+
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
116+
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG
117+
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI
118+
2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx
119+
1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ
120+
q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz
121+
tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ
122+
vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP
123+
BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV
124+
5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY
125+
1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4
126+
NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG
127+
Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91
128+
8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe
129+
pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl
130+
MrY=
131+
-----END CERTIFICATE-----
132+
)EOF";
133+
```
134+
135+
### Connecting to the MQTT Broker
136+
137+
The `connectToMQTT()` function is responsible for establishing a connection to the MQTT broker using TLS. It sets the CA certificate and then attempts to connect using the specified broker address, port, and credentials. The function also sets a keep-alive interval to ensure the connection remains active.
138+
139+
```c
140+
void connectToMQTT() {
141+
   esp_client.setCACert(ca_cert);  // Set the CA certificate for secure connection
142+
   mqtt_client.setServer(mqtt_broker, mqtt_port);  // Set the MQTT broker server and port
143+
   mqtt_client.setKeepAlive(60);  // Set the keep-alive interval to 60 seconds
144+
145+
   while (!mqtt_client.connected()) {
146+
       String client_id = "esp32-client-" + String(WiFi.macAddress());  // Generate a unique client ID
147+
       Serial.printf("Connecting to MQTT Broker as %s...\n", client_id.c_str());
148+
       if (mqtt_client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
149+
           Serial.println("Connected to MQTT Broker");
150+
      } else {
151+
           Serial.print("Failed to connect, rc=");
152+
           Serial.print(mqtt_client.state());  // Print the connection state for debugging
153+
           Serial.println(" Retrying in 5 seconds.");
154+
           delay(5000);  // Wait for 5 seconds before retry
155+
156+
ing
157+
      }
158+
  }
159+
}
160+
```
161+
162+
### Publishing Sensor Data
163+
164+
The `publishSensorData()` function reads the soil moisture sensor data, formats it as a JSON object, and publishes it to the specified MQTT topic. This function ensures the data is correctly serialized and sent over the MQTT protocol.
165+
166+
```c
167+
void publishSensorData() {
168+
   StaticJsonDocument<200> json_doc;
169+
   int moistureValue = analogRead(sensorPIN);  // Read the moisture sensor value
170+
   json_doc["moisture"] = moistureValue;  // Add the sensor value to the JSON document
171+
172+
   char json_buffer[512];
173+
   serializeJson(json_doc, json_buffer);  // Serialize the JSON document to a string
174+
   mqtt_client.publish(mqtt_topic, json_buffer);  // Publish the JSON string to the MQTT topic
175+
   Serial.printf("Published to %s: %d\n", mqtt_topic, moistureValue);  // Print the published message for debugging
176+
}
177+
```
178+
179+
### Complete Code
180+
181+
Here's the complete code with the functions and explanations combined:
182+
183+
```c
184+
#include <WiFi.h>
185+
#include <PubSubClient.h>
186+
#include <WiFiClientSecure.h>
187+
#include <ArduinoJson.h>
188+
189+
// WiFi credentials
190+
const char *ssid = "WIFI_SSID"; // Replace with your WiFi name
191+
const char *password = "WIFI_PASSWORD"; // Replace with your WiFi password
192+
193+
// MQTT Broker configuration
194+
const char *mqtt_broker = "broker.emqx.io";
195+
const char *mqtt_topic = "emqx/esp32/moisture";
196+
const char *mqtt_username = "emqx";
197+
const char *mqtt_password = "public";
198+
const int mqtt_port = 8883;
199+
200+
// WiFi and MQTT client initialization
201+
WiFiClientSecure esp_client;
202+
PubSubClient mqtt_client(esp_client);
203+
204+
// GPIO pin for Soil Moisture, ESP32 pin GPIO36 (ADC0) that connects to AOUT pin of moisture sensor
205+
#define sensorPIN 36
206+
207+
// Root CA Certificate
208+
const char *ca_cert = R"EOF(
209+
-----BEGIN CERTIFICATE-----
210+
MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh
211+
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
212+
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH
213+
MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT
214+
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
215+
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG
216+
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI
217+
2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx
218+
1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ
219+
q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz
220+
tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ
221+
vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP
222+
BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV
223+
5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY
224+
1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4
225+
NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG
226+
Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91
227+
8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe
228+
pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl
229+
MrY=
230+
-----END CERTIFICATE-----
231+
)EOF";
232+
233+
// Function Declarations
234+
void connectToWiFi();
235+
void connectToMQTT();
236+
void publishSensorData();
237+
238+
void setup() {
239+
   Serial.begin(115200);
240+
   connectToWiFi();
241+
   connectToMQTT();
242+
}
243+
244+
void connectToWiFi() {
245+
   WiFi.begin(ssid, password);
246+
   Serial.print("Connecting to WiFi");
247+
   while (WiFi.status() != WL_CONNECTED) {
248+
       delay(500);
249+
       Serial.print(".");
250+
  }
251+
   Serial.println("\nConnected to WiFi");
252+
}
253+
254+
void connectToMQTT() {
255+
   esp_client.setCACert(ca_cert);  // Set the CA certificate for secure connection
256+
   mqtt_client.setServer(mqtt_broker, mqtt_port);  // Set the MQTT broker server and port
257+
   mqtt_client.setKeepAlive(60);  // Set the keep-alive interval to 60 seconds
258+
259+
   while (!mqtt_client.connected()) {
260+
       String client_id = "esp32-client-" + String(WiFi.macAddress());  // Generate a unique client ID
261+
       Serial.printf("Connecting to MQTT Broker as %s...\n", client_id.c_str());
262+
       if (mqtt_client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
263+
           Serial.println("Connected to MQTT Broker");
264+
      } else {
265+
           Serial.print("Failed to connect, rc=");
266+
           Serial.print(mqtt_client.state());  // Print the connection state for debugging
267+
           Serial.println(" Retrying in 5 seconds.");
268+
           delay(5000);  // Wait for 5 seconds before retrying
269+
      }
270+
  }
271+
}
272+
273+
void publishSensorData() {
274+
   StaticJsonDocument<200> json_doc;
275+
   int moistureValue = analogRead(sensorPIN);  // Read the moisture sensor value
276+
   json_doc["moisture"] = moistureValue;  // Add the sensor value to the JSON document
277+
278+
   char json_buffer[512];
279+
   serializeJson(json_doc, json_buffer);  // Serialize the JSON document to a string
280+
   mqtt_client.publish(mqtt_topic, json_buffer);  // Publish the JSON string to the MQTT topic
281+
   Serial.printf("Published to %s: %d\n", mqtt_topic, moistureValue);  // Print the published message for debugging
282+
}
283+
284+
void loop() {
285+
   if (!mqtt_client.connected()) {
286+
       connectToMQTT();
287+
  }
288+
   mqtt_client.loop();
289+
290+
   publishSensorData();
291+
   delay(60000); // Delay between readings
292+
}
293+
```
294+
295+
## Connecting and Testing
296+
297+
### Uploading Code to ESP32
298+
299+
Copy the above code into the Arduino IDE, connect your ESP32 to your computer, select the appropriate board and port, and click the upload button to upload the code to the ESP32.
300+
301+
### Reading Sensor Data and Publishing via MQTT
302+
303+
Once the code is uploaded, open the Serial Monitor. You will see logs indicating the ESP32's connection to the Wi-Fi and MQTT Broker, and soil moisture data will be reported every minute.
304+
305+
![Serial Monitor](https://assets.emqx.com/images/e9b1e49651048e852771964b3f2388d4.png)
306+
307+
### Using MQTTX to Subscribe to a Topic and Retrieve Soil Moisture Published by ESP32
308+
309+
We can use the MQTTX desktop MQTT client to connect to `broker.emqx.io` and then subscribe to the `emqx/esp32/moisture` topic to retrieve the soil moisture published by the ESP32.
310+
311+
![MQTTX](https://assets.emqx.com/images/78cfc74b022026457ff0caa5068524af.png)
312+
313+
## Conclusion
314+
315+
In this tutorial, you learned how to use the ESP32 and a soil moisture sensor to collect soil moisture data and report it to a server via the MQTT protocol. This is just the tip of the iceberg for IoT applications. You can build on this project to explore more possibilities, such as adding more sensors to monitor different environmental parameters or integrating them into an agricultural automation system for smart irrigation.
316+
317+
You can delve deeper into the advanced features of MQTT, such as message retention, last will and testament messages, and explore other functionalities of the ESP32 to expand your IoT projects and achieve more complex application scenarios.
318+
319+
320+
321+
<section class="promotion">
322+
<div>
323+
Talk to an Expert
324+
</div>
325+
<a href="https://www.emqx.com/en/contact?product=solutions" class="button is-gradient">Contact Us →</a>
326+
</section>

0 commit comments

Comments
 (0)