\n";
htmlPage += "
Temperature:
\n";
htmlPage += "
" + String(temperature) + " °C
\n";
htmlPage += "
\n";
htmlPage += "\n";
htmlPage += "\n";
server.send(200, "text/html", htmlPage); // Return to HTML page
}
// Handle paths that are not found
void handle_NotFound() {
server.send(404, "text/plain", "Not found"); // 404 error returned
}
```
### 8.8.6 Test Result
After wiring up and uploading the code to the board, connect your mobile device and the ESP32 to the same Wifi and open the serial monitor to set the baud rate to `9600`, and the IP address will show up. If not, please press the reset button and try to reconnect. Visit the IP address and you can access the page showing real time sensor values. If you have a puzzle of how to upload code, please back to Chapter [4.6 Upload Code on Arduino IDE](https://docs.keyestudio.com/projects/KT0303/en/latest/docs/Arduino_Tutorial.html#upload-code-on-arduino-ide).
**Note: Your mobile device must be connected to the same wifi as the ESP32 board, otherwise we may fail to enter the control page. The ESP32 board consumes much power when using WiFi, so an external DC power supply is required to meet its needs. If not, the ESP32 board will keep resetting, causing the code to not run.**


# 9. IOT Projects
Differed from project 8.7 and 8.8, these IOT projects are based on network, which means the WiFi for the ESP32 needs to be able to connect to the Internet. Therefore, as long as connecting to network, our control terminal (a mobile device) can control sensors and modules without a distance limit. For instance, you can water your potted plant, feed your pet or add water to your fish tank on your app even during a business trip…
## 9.1 Warming-up for IoT
### 9.1.1 Introduction
Here we introduce you how to apply IoT by ESP32 board with MQTT protocol. The project covers the basic concept of MQTT protocol, ESP32 WiFi configuration, MQTT client setup and how to transmit message between devices. So you will learn how to connect the ESP32 to an MQTT broker server (such as Mosquitto or Cloud MQTT) and Publish and Subscribe data. In addition, methods of topic management, message formatting, and system security are included.
Through the experiment, whether you are an IoT beginner or an advanced developer, you can easily master how to develop IoT based on MQTT with ESP32, making device communication in your project more efficient.
### 9.1.2 What is MQTT?
**MQTT is a data communication protocol for publishing and subscribing information based on a client-server architecture**.
MQTT features: lightweight, open source, simple and easy to implement.
These features make MQTT ideal for applications where the Internet of Things has a high demand for **low additional overhead** and **low network load occupancy** for information transmission.
**Publish-subscribe model:**

The publish-subscribe model differs from the traditional server-client model.
In the server-client model, clients directly exchange information with endpoints. While in the publish-subscribe model, the message-publishing client (Publisher) and message-receiving client (Subscriber) are loosely coupled. Publishers and subscribers do not communicate directly and remain unaware of each other’s existence. Their communication relies on a third-party (MQTT Broker) server. It filters all received messages from publishers and distribute them to subscribers interested in specific topics.
In the model shown above, the **temperature sensor** acts as a **publisher**, sending temperature data. The MQTT Broker receives these messages and forwards them to subscribers (**computer** or/and **smartphone**) that have subscribed to the temperature topic. If you have a **smartwatch** which hasn’t subscribed to this topic, it won’t receive messages from the sensor. Notably, the roles of publisher and subscriber are interchangeable - the **computer** and **smartphone** could also act as publishers distributing information.
The **publish-subscribe model** eliminates the need for publishers and subscribers to know each other’s IP addresses/ports (they only require a MQTT Broker’s connection details). The broker handles all coordination, enabling asynchronous communication where publishers don’t require subscribers to be simultaneously available. This significantly enhances system scalability to exchange data across exponentially larger device networks.
The MQTT client development is relatively simple, as the message filtering and categorization logic is embedded within it.
### 9.1.3 Public MQTT Broker
Here are some commonly used public MQTT brokers. Since the brokers used here are public, if we fail to connect to it, we can use another one.
`test.mosquitto.org` and `broker.hivemq.com` are two optional commonly used public MQTT brokers.
Test code:
```c
// MQTT broker
const char* mqtt_broker = "test.mosquitto.org"; // a public Mosquitto MQTT broker
const int mqtt_port = 1883;
```
Or:
```c
// MQTT broker
const char* mqtt_broker = "broker.hivemq.com"; // a public Mosquitto MQTT broker
const int mqtt_port = 1883;
```
## 9.2 APP Download and Layout
### 9.2.1 Download APP
For Android, search `IOT MQTT Panel` in Google Play to install the app. Or you can download the app package we provided.

For IOS, open App Store and search `IOT MQTT Panel` to install the app.
Here we demonstrate how to download the App on a Android device.

### 9.2.2 Add Switches



## 9.3 Remote Control LED
### 9.3.1 Introduction
Here we introduce you how to remotely control 3 LEDs(red, green, yellow) by ESP32 board with MQTT protocol. With this project, you will learn how to connect the ESP32 to an MQTT broker server and Publish and Subscribe data to control LED on/off.
Through the experiment, whether you are an IoT beginner or an advanced developer, you can easily master “remote control” based on MQTT with ESP32, making your project more intelligent and flexible.
### 9.3.2 Principle Diagram

### 9.3.3 Components
|  |  |  |
| :---------------------------: | :-----------------------: | :-----------------------------------: |
| ESP32 main board x1 | red led x1 | yellow LED x1 |
|  |  |  |
| green LED x1 | 220Ω resistor x3 | breadboard x1 |
|  |  |  |
| jump wires | USB cable x1 | AA battery x6 (self-provided) |
|  | | |
| battery holder x1 | | |
### 9.3.4 Wiring Diagram
**The ESP32 board consumes much power when using WiFi, so an external DC power supply is required to meet its needs.**

### 9.3.5 Test Code
Before uploading code, please import library first. In this project, it is saved in `lib` file named `PubSubClient.zip`. If you meet trouble during importing libraries, please back to Chapter [4.7 Import Library](https://docs.keyestudio.com/projects/KT0303/en/latest/docs/Arduino_Tutorial.html#import-library).

The test code is saved in `Code` file named `9_3_Control_LED`:

Open `9_3_Control_LED.ino` in Arduino IDE.
You need to modify the name and password of the wifi that the ESP32 development board needs to connect to, so that you can upload the code successful. Otherwise your ESP32 will not be able to connect to the network. (Note that the wifi must be 2.4Ghz, or the ESP32 may fail to connect.)
```c
// Wi-Fi credentials
const char* ssid = "your SSID"; // Wi-Fi SSID, network name
const char* password = "Password"; // Wi-Fi passwords
```
To ensure a unique clientId, you need to rename by adding your own identifier. For example, change `ESP32Client-66557` into `keyes-ESP32Client`. We add a “keyes” brand name.
```c
// Define a unique clientId for the MQTT client
String clientId = "ESP32Client-66557"; // Ensure that the clientId is unique; otherwise, connection conflicts may occur
```
**Test code:**
```c
/*
* Filename: 9_3_Control_LED
* Function: Use network to control the three LEDs on and off
* Compile IDE: ARDUINO 2.3.4
* Author: https://www.keyestudio.com/
*/
#include