經過前 19 章,我們已經陸續學會 ESP32 的 GPIO、ADC、PWM、I²C、SPI、UART、Wi-Fi、Web Server、Bluetooth、MQTT、ESP-NOW、Deep Sleep、OTA 與 Camera。
第 20 章不再只介紹單一功能,而是將前面所學的 ESP32 技術整合成一套完整的:
ESP32 智慧環境監控與遠端控制系統
這套系統同時具備:
- DHT22 溫溼度監測
- LDR 光線感測
- LCD1602 本機顯示
- Relay 繼電器控制
- Buzzer 高溫警報
- LED 自動夜燈
- 實體按鍵控制
- Wi-Fi 網路連線
- ESP32 Web Server
- 手機/PC Web Dashboard
- MQTT IoT 資料上傳
- MQTT 遠端控制
- JSON 狀態資料
- 自動控制
- 手動控制
- OTA 無線更新
- Wi-Fi / MQTT 自動重連
- Non-blocking 多任務程式架構
最終系統架構:
DHT22
│
LDR
│
Button
│
▼
┌───────────┐
│ ESP32 │
└─────┬─────┘
│
┌──────────┼───────────┐
│ │ │
▼ ▼ ▼
LCD1602 Relay Buzzer
│
│
├────────── LED
│
│ Wi-Fi
▼
Web Server
│
├── Temperature
├── Humidity
├── Light
├── Relay ON/OFF
├── AUTO / MANUAL
└── System Status
│
▼
MQTT
│
▼
IoT Server
這一章可以視為整套 ESP32 20 章教材的代表作品。
一、本章整合了哪些 ESP32 技術?
這套專題會真正把前面章節串接起來。
| 技術 | 本章用途 |
|---|---|
| GPIO Output | Relay、Buzzer、LED |
| GPIO Input | Button |
| ADC | LDR 光敏電阻 |
| I²C | LCD1602 |
| Wi-Fi | 連接 Router |
| Web Server | 建立 Dashboard |
| JSON | 傳遞系統狀態 |
| MQTT | IoT Server 上傳與控制 |
| OTA | 無 USB Firmware Update |
| millis() | Non-blocking 排程 |
| Sensor | DHT22、LDR |
| 自動控制 | 溫度、光線 |
| 手動控制 | Web / MQTT / Button |
所以整體已經不是:
ESP32
↓
LED Blink
而是:
Sensor
↓
ESP32 Controller
↓
Local HMI
↓
Automatic Control
↓
Wi-Fi
↓
Web
↓
MQTT
↓
IoT Server
二、本章完整功能需求
系統需要做到以下功能。
環境感測
ESP32 每隔約 2.5 秒讀取:
Temperature
Humidity
Light
本機顯示
LCD1602 顯示:
T:26.4 H:63.2
L:045 R:OFF A
其中:
T = Temperature
H = Humidity
L = Light
R = Relay
A = Auto Mode
M = Manual Mode
自動控制 Relay
例如 Relay 接風扇。
設定:
Temperature >= 30°C
→ Relay ON
溫度下降:
Temperature <= 28°C
→ Relay OFF
使用:
Hysteresis 遲滯控制
避免 Relay 在 29.9 / 30.0°C 附近不斷跳動。
三、為什麼要加入 Hysteresis?
如果只寫:
if (temperature >= 30) {
relayOn();
} else {
relayOff();
}
當溫度在:
29.9
30.0
29.9
30.0
來回變化時:
Relay ON
Relay OFF
Relay ON
Relay OFF
繼電器會頻繁動作。
較好的方式:
>= 30°C
→ ON
<= 28°C
→ OFF
28~30°C
→ 保持原狀態
這就是:
Hysteresis Control。
四、光線自動控制
LDR 負責偵測環境亮度。
例如:
Light < 25%
→ LED ON
當環境變亮:
Light > 30%
→ LED OFF
同樣保留一小段 Hysteresis。
因此:
晚上
↓
LED ON
白天
↓
LED OFF
形成基本:
自動感光夜燈。
五、高溫 Buzzer 警報
例如設定:
Temperature >= 32°C
ESP32:
Buzzer ON
溫度降回:
Temperature <= 31°C
則:
Buzzer OFF
流程:
DHT22
↓
Temperature
↓
>= 32°C ?
├── YES → Buzzer Alarm
└── NO → Normal
六、AUTO 與 MANUAL 模式
完整控制系統不能只有自動。
本章加入兩種模式。
AUTO
由 Sensor 自動控制 Relay:
Temperature
↓
ESP32 Logic
↓
Relay
MANUAL
使用:
Web
MQTT
Button
控制 Relay。
例如:
Web
↓
Relay ON
此時 ESP32 自動切換:
AUTO
↓
MANUAL
避免自動邏輯下一秒又把 Relay 關掉。
七、實體按鍵功能
Button 接 GPIO32。
每按一次:
Button
↓
MANUAL Mode
↓
Toggle Relay
例如:
Relay OFF
↓
按一下
↓
Relay ON
再按:
Relay ON
↓
按一下
↓
Relay OFF
這表示即使:
Wi-Fi 壞掉
MQTT Server Offline
Web 無法使用
設備仍然可以本機操作。
這是 IoT 系統很重要的設計原則:
網路故障不能讓基本設備完全失去控制能力。
八、所需硬體
| 元件 | 數量 |
|---|---|
| ESP32-WROOM-32 DevKit | 1 |
| DHT22 | 1 |
| LDR 光敏電阻 | 1 |
| 10kΩ 電阻 | 1~2 |
| LCD1602 I²C | 1 |
| Relay Module | 1 |
| Active Buzzer | 1 |
| LED | 1 |
| 220Ω 電阻 | 1 |
| Push Button | 1 |
| 麵包板 | 1 |
| 杜邦線 | 若干 |
九、本章 ESP32 Pin 配置
本章以經典:
ESP32-WROOM-32 DevKit
為例。
| 功能 | GPIO |
|---|---|
| DHT22 DATA | GPIO4 |
| LDR ADC | GPIO34 |
| Button | GPIO32 |
| LCD SDA | GPIO21 |
| LCD SCL | GPIO22 |
| Relay | GPIO26 |
| Buzzer | GPIO27 |
| LED | GPIO2 |
十、為什麼 LDR 選 GPIO34?
這是一個很重要的 ESP32 實務問題。
GPIO34 屬於:
ADC1
而不是 ADC2。
經典 ESP32 的 ADC2 會與 Wi-Fi Driver 共用資源;Espressif 官方文件目前仍明確提醒,使用 Wi-Fi 時 ADC2 Pin 會有使用限制,若 Wi-Fi 運作期間需要 Analog Input,應優先考慮 ADC1。GPIO34~39 另外屬於 Input-only GPIO,正好很適合 LDR 類比輸入。
因此本章:
Wi-Fi
+
LDR
使用:
GPIO34
會比隨意使用 ADC2 GPIO 更適合。
十一、DHT22 接線
DHT22:
| DHT22 | ESP32 |
|---|---|
| VCC | 3.3V |
| DATA | GPIO4 |
| GND | GND |
如果使用裸 DHT22,可以加入:
3.3V
│
10kΩ
│
├──── DATA
│ │
│ GPIO4
│
DHT22
也就是:
DATA 與 VCC 之間加入約 4.7kΩ~10kΩ Pull-up。
十二、LDR 光敏電阻接線
本章使用 Voltage Divider。
3.3V
│
LDR
│
├──────── GPIO34
│
10kΩ
│
GND
也就是:
3.3V
↓
LDR
↓
GPIO34
↓
10kΩ
↓
GND
此接法通常:
越亮
→ GPIO34 Voltage 越高
→ ADC Raw 越高
因此:
lightPercent =
ldrRaw / 4095.0 * 100.0;
可換算成約:
0~100%
的相對亮度。
注意:
這不是 Lux Meter。
LDR、電阻誤差與 ESP32 ADC 非線性都會影響實際結果。
如果需要真正:
Lux
建議使用:
BH1750
等數位光照感測器。
十三、LDR 電壓不能超過 ESP32 GPIO
ESP32 GPIO 為:
3.3V Logic。
所以 Voltage Divider 上端使用:
3.3V
而不是:
5V
避免 ADC GPIO 接收到過高電壓。
十四、LCD1602 I²C 接線
| LCD1602 I²C | ESP32 |
|---|---|
| SDA | GPIO21 |
| SCL | GPIO22 |
| GND | GND |
| VCC | 依模組規格 |
ESP32 常用:
SDA = GPIO21
SCL = GPIO22
程式:
Wire.begin(
21,
22
);
LCD Address 常見:
0x27
或:
0x3F
本章使用:
LiquidCrystal_I2C lcd(
0x27,
16,
2
);
十五、LCD1602 5V I²C 注意事項
部分 LCD1602 + PCF8574 Backpack:
VCC = 5V
並且 SDA / SCL Pull-up 也可能拉到 5V。
ESP32 GPIO 並不是 5V Tolerant。
因此正式硬體建議確認模組電路,必要時加入:
雙向 I²C Level Shifter
形成:
ESP32 3.3V
│
│ I2C
▼
Level Converter
│
▼
LCD1602 5V
十六、Relay 接線
本章:
Relay IN
→ GPIO26
| Relay | ESP32 |
|---|---|
| IN | GPIO26 |
| GND | GND |
| VCC | 依 Relay Module 規格 |
很多 Relay Module 是:
Active LOW。
也就是:
GPIO LOW
→ Relay ON
GPIO HIGH
→ Relay OFF
所以程式會加入:
#define RELAY_ACTIVE_LOW true
如果你的 Relay 是 Active HIGH:
#define RELAY_ACTIVE_LOW false
即可。
十七、Relay 不可以直接驅動大型負載
ESP32 GPIO 只能提供 Logic Signal。
不能:
GPIO26
↓
直接接馬達
也不能直接:
GPIO26
↓
110V AC
Relay Module 本身應具備:
- Driver Transistor
- Flyback Diode
- Optocoupler(部分模組)
- Relay Coil Driver
如果控制 AC 市電,更必須注意:
高壓電安全、絕緣距離、保險絲與外殼。
十八、Buzzer 接線
本章使用:
Active Buzzer。
GPIO27
↓
Active Buzzer
↓
GND
如果 Buzzer 模組所需電流超過 ESP32 GPIO 能直接提供的範圍,應使用:
GPIO27
↓
Transistor / MOSFET
↓
Buzzer
本章程式只使用:
digitalWrite()
所以假設使用:
Active Buzzer / Buzzer Module。
十九、LED 接線
GPIO2
↓
220Ω
↓
LED
↓
GND
部分 ESP32 DevKit 本身 GPIO2 已有 LED,則可以直接使用內建 LED 測試。
二十、Button 接線
本章:
GPIO32
↓
Button
↓
GND
程式使用:
pinMode(
BUTTON_PIN,
INPUT_PULLUP
);
所以平常:
HIGH
按下:
LOW
不需要另外接外部 Pull-up。
二十一、本章軟體架構
整個程式不應該寫成:
readSensor();
delay(5000);
connectMQTT();
delay(5000);
updateLCD();
delay(5000);
因為長時間 delay() 會阻塞:
- Web Server
- MQTT
- OTA
- Button
- Sensor
- Wi-Fi reconnect
所以本章改成:
Non-blocking Architecture
核心:
millis()
流程:
loop()
│
├── server.handleClient()
│
├── ArduinoOTA.handle()
│
├── mqttClient.loop()
│
├── handleSensors()
│
├── handleButton()
│
├── handleAutomaticControl()
│
├── updateLCD()
│
├── publishMQTT()
│
└── reconnectNetwork()
每一次 loop() 都很快結束。
二十二、需要安裝哪些 Library?
需要:
DHT sensor library
LiquidCrystal_I2C
PubSubClient
ESP32 Core 已提供:
WiFi.h
WebServer.h
ArduinoOTA.h
Wire.h
二十三、關於 PubSubClient 的 2026 注意事項
為了和前面 MQTT 教材及大量 Arduino 範例保持一致,本章完整程式仍示範:
#include <PubSubClient.h>
不過截至 2026 年,PubSubClient 原作者已在官方 Repository README 明確標示該 Library 不再維護,並建議新專案選擇仍積極維護的替代方案。它目前仍支援 ESP32、MQTT 3.1.1,預設 Packet Buffer 為 256 bytes,而且 Publish 端主要為 QoS 0。
因此建議:
教材 / 實驗
→ PubSubClient 可以繼續使用
新產品 / 長期維護
→ 評估 ESP-MQTT 或其他維護中的 MQTT Client
Espressif 官方的 ESP-MQTT 目前支援 MQTT v5.0、TCP、TLS、WebSocket / WSS、Authentication、Last Will 與三種 QoS。
二十四、MQTT Topic 規劃
本章設定:
esp32/environment/status
發布完整 JSON。
Relay Control:
esp32/environment/relay/set
Payload:
ON
或:
OFF
控制模式:
esp32/environment/mode/set
Payload:
AUTO
或:
MANUAL
在線狀態:
esp32/environment/availability
內容:
online
offline
二十五、MQTT JSON 格式
ESP32 定時 Publish:
{
"device": "esp32-env-01",
"temperature": 26.4,
"humidity": 63.2,
"light": 47,
"ldr_raw": 1934,
"relay": true,
"led": false,
"alarm": false,
"mode": "AUTO",
"wifi_rssi": -51
}
IoT Server 可以直接拿這份 JSON:
MQTT
↓
Node-RED
↓
Database
↓
Grafana
或者:
MQTT
↓
Home Assistant
建立 Dashboard。
二十六、Web Dashboard 功能
手機或 Windows 11 Browser 開:
http://ESP32-IP/
Dashboard 顯示:
Temperature
Humidity
Light
Relay
Alarm
Mode
Wi-Fi RSSI
MQTT
Firmware Version
另外提供:
Relay ON
Relay OFF
AUTO
MANUAL
四個控制按鈕。
二十七、Web Dashboard 不重新整理整頁
如果每兩秒:
Reload Page
使用體驗很差。
所以本章使用:
fetch('/api/status')
取得 JSON。
流程:
Browser
↓
GET /api/status
↓
ESP32
↓
JSON
↓
JavaScript
↓
更新 Dashboard
每:
2 秒
更新一次。
二十八、完整 ESP32 智慧環境監控程式
下面就是整套 20 章教材最後的完整實作。
請先修改:
Wi-Fi SSID
Wi-Fi Password
MQTT Broker IP
MQTT Username
MQTT Password
OTA Password
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <PubSubClient.h>
#include <ArduinoOTA.h>
// =====================================================
// Firmware Information
// =====================================================
const char* DEVICE_NAME =
"ESP32-ENV-01";
const char* FIRMWARE_VERSION =
"1.0.0";
// =====================================================
// Wi-Fi
// =====================================================
const char* WIFI_SSID =
"YOUR_WIFI_SSID";
const char* WIFI_PASSWORD =
"YOUR_WIFI_PASSWORD";
// =====================================================
// MQTT
// =====================================================
const char* MQTT_HOST =
"192.168.1.100";
const uint16_t MQTT_PORT =
1883;
// 如果 Broker 沒有帳號密碼,可以設成 ""
const char* MQTT_USER =
"";
const char* MQTT_PASSWORD =
"";
// MQTT Topics
const char* TOPIC_STATUS =
"esp32/environment/status";
const char* TOPIC_RELAY_SET =
"esp32/environment/relay/set";
const char* TOPIC_MODE_SET =
"esp32/environment/mode/set";
const char* TOPIC_AVAILABILITY =
"esp32/environment/availability";
// =====================================================
// OTA
// =====================================================
const char* OTA_HOSTNAME =
"esp32-env-01";
const char* OTA_PASSWORD =
"ChangeThisOTAPassword";
// =====================================================
// GPIO
// =====================================================
#define DHT_PIN 4
#define DHT_TYPE DHT22
#define LDR_PIN 34
#define BUTTON_PIN 32
#define RELAY_PIN 26
#define BUZZER_PIN 27
#define LED_PIN 2
// =====================================================
// I2C
// =====================================================
#define I2C_SDA 21
#define I2C_SCL 22
// =====================================================
// Relay
// =====================================================
#define RELAY_ACTIVE_LOW true
// =====================================================
// Control Threshold
// =====================================================
// Relay / Fan
const float RELAY_TEMP_ON =
30.0;
const float RELAY_TEMP_OFF =
28.0;
// Temperature Alarm
const float ALARM_TEMP_ON =
32.0;
const float ALARM_TEMP_OFF =
31.0;
// Auto Light
const float LIGHT_LED_ON =
25.0;
const float LIGHT_LED_OFF =
30.0;
// =====================================================
// Timers
// =====================================================
const unsigned long SENSOR_INTERVAL =
2500;
const unsigned long LCD_INTERVAL =
1000;
const unsigned long MQTT_PUBLISH_INTERVAL =
5000;
const unsigned long MQTT_RECONNECT_INTERVAL =
5000;
const unsigned long WIFI_RECONNECT_INTERVAL =
10000;
const unsigned long BUTTON_DEBOUNCE =
50;
// =====================================================
// Objects
// =====================================================
DHT dht(
DHT_PIN,
DHT_TYPE
);
LiquidCrystal_I2C lcd(
0x27,
16,
2
);
WebServer server(
80
);
WiFiClient wifiClient;
PubSubClient mqttClient(
wifiClient
);
// =====================================================
// System State
// =====================================================
enum ControlMode {
MODE_AUTO,
MODE_MANUAL
};
ControlMode controlMode =
MODE_AUTO;
float temperature =
0.0;
float humidity =
0.0;
int ldrRaw =
0;
float lightPercent =
0.0;
bool sensorValid =
false;
bool relayState =
false;
bool ledState =
false;
bool alarmState =
false;
bool mqttConnected =
false;
bool otaStarted =
false;
// =====================================================
// Timer State
// =====================================================
unsigned long lastSensorMillis =
0;
unsigned long lastLCDMillis =
0;
unsigned long lastMQTTPublishMillis =
0;
unsigned long lastMQTTReconnectMillis =
0;
unsigned long lastWiFiReconnectMillis =
0;
// =====================================================
// Button State
// =====================================================
bool lastButtonReading =
HIGH;
bool stableButtonState =
HIGH;
unsigned long lastButtonChangeMillis =
0;
// =====================================================
// Web Page
// =====================================================
const char INDEX_HTML[] PROGMEM =
R"rawliteral(
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta
name="viewport"
content="width=device-width, initial-scale=1">
<title>
ESP32 Smart Environment
</title>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 20px;
font-family:
Arial,
"Microsoft JhengHei",
sans-serif;
background: #f4f6f8;
color: #222;
}
.container {
max-width: 900px;
margin: auto;
}
h1 {
text-align: center;
}
.grid {
display: grid;
grid-template-columns:
repeat(
auto-fit,
minmax(180px, 1fr)
);
gap: 14px;
}
.card {
background: white;
border-radius: 12px;
padding: 18px;
box-shadow:
0 2px 10px
rgba(0,0,0,0.08);
}
.label {
font-size: 14px;
color: #666;
}
.value {
font-size: 28px;
font-weight: bold;
margin-top: 8px;
}
.control {
margin-top: 20px;
background: white;
border-radius: 12px;
padding: 18px;
box-shadow:
0 2px 10px
rgba(0,0,0,0.08);
}
button {
border: none;
padding: 12px 18px;
margin: 5px;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
}
.on {
background: #198754;
color: white;
}
.off {
background: #dc3545;
color: white;
}
.auto {
background: #0d6efd;
color: white;
}
.manual {
background: #6c757d;
color: white;
}
.status {
margin-top: 20px;
font-size: 14px;
color: #555;
}
</style>
</head>
<body>
<div class="container">
<h1>
ESP32 智慧環境監控
</h1>
<div class="grid">
<div class="card">
<div class="label">
溫度
</div>
<div
class="value"
id="temperature">
--
</div>
</div>
<div class="card">
<div class="label">
濕度
</div>
<div
class="value"
id="humidity">
--
</div>
</div>
<div class="card">
<div class="label">
光線
</div>
<div
class="value"
id="light">
--
</div>
</div>
<div class="card">
<div class="label">
Relay
</div>
<div
class="value"
id="relay">
--
</div>
</div>
<div class="card">
<div class="label">
控制模式
</div>
<div
class="value"
id="mode">
--
</div>
</div>
<div class="card">
<div class="label">
Alarm
</div>
<div
class="value"
id="alarm">
--
</div>
</div>
</div>
<div class="control">
<h2>
Relay Control
</h2>
<button
class="on"
onclick="command('/relay/on')">
Relay ON
</button>
<button
class="off"
onclick="command('/relay/off')">
Relay OFF
</button>
<button
class="auto"
onclick="command('/mode/auto')">
AUTO
</button>
<button
class="manual"
onclick="command('/mode/manual')">
MANUAL
</button>
</div>
<div
class="status"
id="systemStatus">
Loading...
</div>
</div>
<script>
async function command(url) {
try {
await fetch(url);
await updateStatus();
} catch (e) {
console.log(e);
}
}
async function updateStatus() {
try {
const response =
await fetch(
'/api/status'
);
const data =
await response.json();
document.getElementById(
'temperature'
).textContent =
data.temperature === null
? '--'
: data.temperature +
' °C';
document.getElementById(
'humidity'
).textContent =
data.humidity === null
? '--'
: data.humidity +
' %';
document.getElementById(
'light'
).textContent =
data.light +
' %';
document.getElementById(
'relay'
).textContent =
data.relay
? 'ON'
: 'OFF';
document.getElementById(
'mode'
).textContent =
data.mode;
document.getElementById(
'alarm'
).textContent =
data.alarm
? 'ALARM'
: 'NORMAL';
document.getElementById(
'systemStatus'
).innerHTML =
'Wi-Fi RSSI: ' +
data.wifi_rssi +
' dBm' +
' | MQTT: ' +
(
data.mqtt
? 'Connected'
: 'Disconnected'
) +
' | Firmware: ' +
data.firmware;
} catch (e) {
document.getElementById(
'systemStatus'
).textContent =
'ESP32 connection failed';
}
}
updateStatus();
setInterval(
updateStatus,
2000
);
</script>
</body>
</html>
)rawliteral";
// =====================================================
// Utility
// =====================================================
const char* getModeName() {
return (
controlMode ==
MODE_AUTO
)
? "AUTO"
: "MANUAL";
}
// =====================================================
// Relay Control
// =====================================================
void setRelay(
bool on
) {
relayState =
on;
if (
RELAY_ACTIVE_LOW
) {
digitalWrite(
RELAY_PIN,
on
? LOW
: HIGH
);
} else {
digitalWrite(
RELAY_PIN,
on
? HIGH
: LOW
);
}
Serial.print(
"Relay: "
);
Serial.println(
on
? "ON"
: "OFF"
);
}
// =====================================================
// LED Control
// =====================================================
void setLED(
bool on
) {
ledState =
on;
digitalWrite(
LED_PIN,
on
? HIGH
: LOW
);
}
// =====================================================
// Alarm Control
// =====================================================
void setAlarm(
bool on
) {
if (
alarmState ==
on
) {
return;
}
alarmState =
on;
digitalWrite(
BUZZER_PIN,
on
? HIGH
: LOW
);
Serial.print(
"Alarm: "
);
Serial.println(
on
? "ON"
: "OFF"
);
}
// =====================================================
// Sensor Read
// =====================================================
void readSensors() {
float newHumidity =
dht.readHumidity();
float newTemperature =
dht.readTemperature();
ldrRaw =
analogRead(
LDR_PIN
);
lightPercent =
(
(float)ldrRaw /
4095.0
) *
100.0;
lightPercent =
constrain(
lightPercent,
0.0,
100.0
);
if (
isnan(
newHumidity
) ||
isnan(
newTemperature
)
) {
sensorValid =
false;
Serial.println(
"DHT22 Read Failed"
);
return;
}
sensorValid =
true;
temperature =
newTemperature;
humidity =
newHumidity;
Serial.println();
Serial.println(
"------------------------"
);
Serial.print(
"Temperature: "
);
Serial.print(
temperature,
1
);
Serial.println(
" C"
);
Serial.print(
"Humidity: "
);
Serial.print(
humidity,
1
);
Serial.println(
" %"
);
Serial.print(
"LDR Raw: "
);
Serial.println(
ldrRaw
);
Serial.print(
"Light: "
);
Serial.print(
lightPercent,
1
);
Serial.println(
" %"
);
}
// =====================================================
// Automatic Control
// =====================================================
void handleAutomaticControl() {
// -----------------------------------------------
// High Temperature Alarm
// Alarm 和 AUTO/MANUAL 無關
// -----------------------------------------------
if (
sensorValid
) {
if (
!alarmState &&
temperature >=
ALARM_TEMP_ON
) {
setAlarm(
true
);
} else if (
alarmState &&
temperature <=
ALARM_TEMP_OFF
) {
setAlarm(
false
);
}
}
// -----------------------------------------------
// Automatic Light
// -----------------------------------------------
if (
!ledState &&
lightPercent <=
LIGHT_LED_ON
) {
setLED(
true
);
} else if (
ledState &&
lightPercent >=
LIGHT_LED_OFF
) {
setLED(
false
);
}
// -----------------------------------------------
// Relay only AUTO
// -----------------------------------------------
if (
controlMode !=
MODE_AUTO
) {
return;
}
if (
!sensorValid
) {
return;
}
if (
!relayState &&
temperature >=
RELAY_TEMP_ON
) {
setRelay(
true
);
} else if (
relayState &&
temperature <=
RELAY_TEMP_OFF
) {
setRelay(
false
);
}
}
// =====================================================
// Button
// =====================================================
void handleButton() {
bool reading =
digitalRead(
BUTTON_PIN
);
if (
reading !=
lastButtonReading
) {
lastButtonChangeMillis =
millis();
lastButtonReading =
reading;
}
if (
millis() -
lastButtonChangeMillis >
BUTTON_DEBOUNCE
) {
if (
stableButtonState !=
reading
) {
stableButtonState =
reading;
if (
stableButtonState ==
LOW
) {
// Button 進入手動模式
controlMode =
MODE_MANUAL;
setRelay(
!relayState
);
Serial.println(
"Button -> MANUAL"
);
publishMQTTStatus();
}
}
}
}
// =====================================================
// LCD
// =====================================================
void updateLCD() {
char line1[17];
char line2[17];
if (
sensorValid
) {
snprintf(
line1,
sizeof(line1),
"T:%4.1f H:%4.1f",
temperature,
humidity
);
} else {
snprintf(
line1,
sizeof(line1),
"DHT22 ERROR "
);
}
int lightValue =
(int)lightPercent;
snprintf(
line2,
sizeof(line2),
"L:%03d R:%s %c",
lightValue,
relayState
? "ON"
: "OF",
controlMode ==
MODE_AUTO
? 'A'
: 'M'
);
lcd.setCursor(
0,
0
);
lcd.print(
" "
);
lcd.setCursor(
0,
0
);
lcd.print(
line1
);
lcd.setCursor(
0,
1
);
lcd.print(
" "
);
lcd.setCursor(
0,
1
);
lcd.print(
line2
);
}
// =====================================================
// JSON
// =====================================================
String buildStatusJSON() {
String json =
"{";
json +=
"\"device\":\"";
json +=
DEVICE_NAME;
json +=
"\",";
json +=
"\"temperature\":";
if (
sensorValid
) {
json +=
String(
temperature,
1
);
} else {
json +=
"null";
}
json +=
",";
json +=
"\"humidity\":";
if (
sensorValid
) {
json +=
String(
humidity,
1
);
} else {
json +=
"null";
}
json +=
",";
json +=
"\"light\":";
json +=
String(
lightPercent,
1
);
json +=
",";
json +=
"\"ldr_raw\":";
json +=
String(
ldrRaw
);
json +=
",";
json +=
"\"relay\":";
json +=
relayState
? "true"
: "false";
json +=
",";
json +=
"\"led\":";
json +=
ledState
? "true"
: "false";
json +=
",";
json +=
"\"alarm\":";
json +=
alarmState
? "true"
: "false";
json +=
",";
json +=
"\"mode\":\"";
json +=
getModeName();
json +=
"\",";
json +=
"\"wifi_rssi\":";
if (
WiFi.status() ==
WL_CONNECTED
) {
json +=
String(
WiFi.RSSI()
);
} else {
json +=
"0";
}
json +=
",";
json +=
"\"mqtt\":";
json +=
mqttClient.connected()
? "true"
: "false";
json +=
",";
json +=
"\"firmware\":\"";
json +=
FIRMWARE_VERSION;
json +=
"\"";
json +=
"}";
return json;
}
// =====================================================
// MQTT Publish
// =====================================================
void publishMQTTStatus() {
if (
!mqttClient.connected()
) {
return;
}
String payload =
buildStatusJSON();
mqttClient.publish(
TOPIC_STATUS,
payload.c_str(),
true
);
Serial.println(
"MQTT Publish:"
);
Serial.println(
payload
);
}
// =====================================================
// MQTT Callback
// =====================================================
void mqttCallback(
char* topic,
byte* payload,
unsigned int length
) {
String message;
for (
unsigned int i = 0;
i < length;
i++
) {
message +=
(char)payload[i];
}
message.trim();
message.toUpperCase();
Serial.print(
"MQTT Topic: "
);
Serial.println(
topic
);
Serial.print(
"MQTT Payload: "
);
Serial.println(
message
);
// -----------------------------------------------
// Relay Command
// -----------------------------------------------
if (
String(topic) ==
TOPIC_RELAY_SET
) {
if (
message ==
"ON"
) {
controlMode =
MODE_MANUAL;
setRelay(
true
);
} else if (
message ==
"OFF"
) {
controlMode =
MODE_MANUAL;
setRelay(
false
);
}
}
// -----------------------------------------------
// Mode
// -----------------------------------------------
if (
String(topic) ==
TOPIC_MODE_SET
) {
if (
message ==
"AUTO"
) {
controlMode =
MODE_AUTO;
} else if (
message ==
"MANUAL"
) {
controlMode =
MODE_MANUAL;
}
}
publishMQTTStatus();
}
// =====================================================
// MQTT Connect
// =====================================================
void connectMQTT() {
if (
WiFi.status() !=
WL_CONNECTED
) {
return;
}
if (
mqttClient.connected()
) {
return;
}
String clientId =
"ESP32-ENV-";
String mac =
WiFi.macAddress();
mac.replace(
":",
""
);
clientId +=
mac;
Serial.print(
"MQTT connecting: "
);
Serial.println(
clientId
);
bool connected =
false;
if (
strlen(
MQTT_USER
) > 0
) {
connected =
mqttClient.connect(
clientId.c_str(),
MQTT_USER,
MQTT_PASSWORD,
TOPIC_AVAILABILITY,
1,
true,
"offline"
);
} else {
connected =
mqttClient.connect(
clientId.c_str(),
TOPIC_AVAILABILITY,
1,
true,
"offline"
);
}
if (
connected
) {
Serial.println(
"MQTT Connected"
);
mqttConnected =
true;
mqttClient.publish(
TOPIC_AVAILABILITY,
"online",
true
);
mqttClient.subscribe(
TOPIC_RELAY_SET
);
mqttClient.subscribe(
TOPIC_MODE_SET
);
publishMQTTStatus();
} else {
mqttConnected =
false;
Serial.print(
"MQTT Failed, state="
);
Serial.println(
mqttClient.state()
);
}
}
// =====================================================
// Wi-Fi
// =====================================================
void connectWiFi() {
Serial.println();
Serial.print(
"Connecting Wi-Fi: "
);
Serial.println(
WIFI_SSID
);
WiFi.mode(
WIFI_STA
);
WiFi.setAutoReconnect(
true
);
WiFi.begin(
WIFI_SSID,
WIFI_PASSWORD
);
unsigned long start =
millis();
while (
WiFi.status() !=
WL_CONNECTED &&
millis() - start <
15000
) {
delay(
250
);
Serial.print(
"."
);
}
Serial.println();
if (
WiFi.status() ==
WL_CONNECTED
) {
Serial.println(
"Wi-Fi Connected"
);
Serial.print(
"IP: "
);
Serial.println(
WiFi.localIP()
);
Serial.print(
"RSSI: "
);
Serial.print(
WiFi.RSSI()
);
Serial.println(
" dBm"
);
} else {
Serial.println(
"Wi-Fi Connect Timeout"
);
}
}
// =====================================================
// OTA
// =====================================================
void setupOTA() {
if (
otaStarted
) {
return;
}
ArduinoOTA.setHostname(
OTA_HOSTNAME
);
ArduinoOTA.setPassword(
OTA_PASSWORD
);
ArduinoOTA.onStart(
[]() {
Serial.println();
Serial.println(
"OTA Start"
);
// OTA 期間先讓 Relay 進安全狀態
setRelay(
false
);
setAlarm(
false
);
}
);
ArduinoOTA.onEnd(
[]() {
Serial.println();
Serial.println(
"OTA Complete"
);
}
);
ArduinoOTA.onProgress(
[](
unsigned int progress,
unsigned int total
) {
unsigned int percent =
(
progress * 100U
) /
total;
Serial.printf(
"OTA: %u%%\r",
percent
);
}
);
ArduinoOTA.onError(
[](
ota_error_t error
) {
Serial.printf(
"OTA Error [%u]\n",
error
);
}
);
ArduinoOTA.begin();
otaStarted =
true;
Serial.println(
"ArduinoOTA Ready"
);
Serial.print(
"OTA Hostname: "
);
Serial.println(
OTA_HOSTNAME
);
}
// =====================================================
// Web Handlers
// =====================================================
void handleRoot() {
server.send(
200,
"text/html; charset=utf-8",
INDEX_HTML
);
}
void handleAPIStatus() {
server.send(
200,
"application/json",
buildStatusJSON()
);
}
void handleRelayOn() {
controlMode =
MODE_MANUAL;
setRelay(
true
);
publishMQTTStatus();
server.send(
200,
"application/json",
buildStatusJSON()
);
}
void handleRelayOff() {
controlMode =
MODE_MANUAL;
setRelay(
false
);
publishMQTTStatus();
server.send(
200,
"application/json",
buildStatusJSON()
);
}
void handleAutoMode() {
controlMode =
MODE_AUTO;
handleAutomaticControl();
publishMQTTStatus();
server.send(
200,
"application/json",
buildStatusJSON()
);
}
void handleManualMode() {
controlMode =
MODE_MANUAL;
publishMQTTStatus();
server.send(
200,
"application/json",
buildStatusJSON()
);
}
void setupWebServer() {
server.on(
"/",
HTTP_GET,
handleRoot
);
server.on(
"/api/status",
HTTP_GET,
handleAPIStatus
);
server.on(
"/relay/on",
HTTP_GET,
handleRelayOn
);
server.on(
"/relay/off",
HTTP_GET,
handleRelayOff
);
server.on(
"/mode/auto",
HTTP_GET,
handleAutoMode
);
server.on(
"/mode/manual",
HTTP_GET,
handleManualMode
);
server.onNotFound(
[]() {
server.send(
404,
"text/plain",
"404 Not Found"
);
}
);
server.begin();
Serial.println(
"Web Server Started"
);
}
// =====================================================
// Reconnect Services
// =====================================================
void handleWiFiReconnect() {
if (
WiFi.status() ==
WL_CONNECTED
) {
if (
!otaStarted
) {
setupOTA();
}
return;
}
if (
millis() -
lastWiFiReconnectMillis <
WIFI_RECONNECT_INTERVAL
) {
return;
}
lastWiFiReconnectMillis =
millis();
Serial.println(
"Wi-Fi reconnect..."
);
WiFi.disconnect();
WiFi.begin(
WIFI_SSID,
WIFI_PASSWORD
);
}
void handleMQTTReconnect() {
if (
WiFi.status() !=
WL_CONNECTED
) {
return;
}
if (
mqttClient.connected()
) {
return;
}
if (
millis() -
lastMQTTReconnectMillis <
MQTT_RECONNECT_INTERVAL
) {
return;
}
lastMQTTReconnectMillis =
millis();
connectMQTT();
}
// =====================================================
// Setup
// =====================================================
void setup() {
Serial.begin(
115200
);
delay(
500
);
Serial.println();
Serial.println(
"================================"
);
Serial.println(
"ESP32 Smart Environment System"
);
Serial.print(
"Firmware: "
);
Serial.println(
FIRMWARE_VERSION
);
Serial.println(
"================================"
);
// -----------------------------------------------
// GPIO
// -----------------------------------------------
pinMode(
RELAY_PIN,
OUTPUT
);
pinMode(
BUZZER_PIN,
OUTPUT
);
pinMode(
LED_PIN,
OUTPUT
);
pinMode(
BUTTON_PIN,
INPUT_PULLUP
);
pinMode(
LDR_PIN,
INPUT
);
// -----------------------------------------------
// Safe Startup
// -----------------------------------------------
setRelay(
false
);
setLED(
false
);
setAlarm(
false
);
// -----------------------------------------------
// DHT
// -----------------------------------------------
dht.begin();
// -----------------------------------------------
// I2C LCD
// -----------------------------------------------
Wire.begin(
I2C_SDA,
I2C_SCL
);
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(
0,
0
);
lcd.print(
"ESP32 IoT System"
);
lcd.setCursor(
0,
1
);
lcd.print(
"Starting..."
);
// -----------------------------------------------
// Wi-Fi
// -----------------------------------------------
connectWiFi();
// -----------------------------------------------
// Web Server
// -----------------------------------------------
setupWebServer();
// -----------------------------------------------
// MQTT
// -----------------------------------------------
mqttClient.setServer(
MQTT_HOST,
MQTT_PORT
);
mqttClient.setCallback(
mqttCallback
);
// JSON 留較充足空間
mqttClient.setBufferSize(
512
);
if (
WiFi.status() ==
WL_CONNECTED
) {
connectMQTT();
setupOTA();
}
// -----------------------------------------------
// First Sensor Reading
// -----------------------------------------------
readSensors();
handleAutomaticControl();
updateLCD();
Serial.println();
if (
WiFi.status() ==
WL_CONNECTED
) {
Serial.println(
"Web Dashboard:"
);
Serial.print(
"http://"
);
Serial.println(
WiFi.localIP()
);
}
}
// =====================================================
// Loop
// =====================================================
void loop() {
unsigned long now =
millis();
// -----------------------------------------------
// Web Server
// -----------------------------------------------
server.handleClient();
// -----------------------------------------------
// OTA
// -----------------------------------------------
if (
otaStarted &&
WiFi.status() ==
WL_CONNECTED
) {
ArduinoOTA.handle();
}
// -----------------------------------------------
// MQTT
// -----------------------------------------------
if (
mqttClient.connected()
) {
mqttClient.loop();
}
// -----------------------------------------------
// Button
// -----------------------------------------------
handleButton();
// -----------------------------------------------
// Sensor
// -----------------------------------------------
if (
now -
lastSensorMillis >=
SENSOR_INTERVAL
) {
lastSensorMillis =
now;
readSensors();
handleAutomaticControl();
}
// -----------------------------------------------
// LCD
// -----------------------------------------------
if (
now -
lastLCDMillis >=
LCD_INTERVAL
) {
lastLCDMillis =
now;
updateLCD();
}
// -----------------------------------------------
// MQTT Publish
// -----------------------------------------------
if (
now -
lastMQTTPublishMillis >=
MQTT_PUBLISH_INTERVAL
) {
lastMQTTPublishMillis =
now;
publishMQTTStatus();
}
// -----------------------------------------------
// Reconnect
// -----------------------------------------------
handleWiFiReconnect();
handleMQTTReconnect();
// 不使用長 delay()
delay(
1
);
}
二十九、完整程式架構解析
這支程式雖然比較長,但其實可以拆成幾個獨立模組:
Sensor
├── readSensors()
└── DHT22 + LDR
Control
├── setRelay()
├── setLED()
├── setAlarm()
└── handleAutomaticControl()
HMI
├── handleButton()
└── updateLCD()
Network
├── connectWiFi()
├── WebServer
└── OTA
MQTT
├── connectMQTT()
├── mqttCallback()
└── publishMQTTStatus()
Main
├── setup()
└── loop()
這已經開始接近真正 Embedded Software 的:
Modular Design。
三十、Sensor 流程
每:
2.5 秒
執行:
readSensors();
讀取:
DHT22
├── Temperature
└── Humidity
LDR
└── Light
然後:
handleAutomaticControl();
決定:
Relay
LED
Buzzer
狀態。
三十一、完整自動控制流程
DHT22
│
▼
Temperature
│
┌───────┼────────┐
│ │
▼ ▼
>= 30°C >= 32°C
│ │
▼ ▼
Relay ON Buzzer ON
│
│
<= 28°C
│
▼
Relay OFF
另外:
LDR
↓
Light %
↓
<= 25%
↓
LED ON
>= 30%
↓
LED OFF
三十二、AUTO 模式實際效果
假設目前:
Temperature = 27°C
Light = 60%
結果:
Relay OFF
LED OFF
Buzzer OFF
晚上:
Temperature = 27°C
Light = 15%
變成:
Relay OFF
LED ON
Buzzer OFF
溫度上升:
Temperature = 30.5°C
則:
Relay ON
如果繼續升到:
32.5°C
則:
Relay ON
Buzzer ON
三十三、Web Relay ON 會發生什麼?
使用 Browser 點:
Relay ON
呼叫:
/relay/on
ESP32:
AUTO
↓
MANUAL
↓
Relay ON
然後立即 Publish MQTT Status。
這樣:
Web
LCD
MQTT
Physical Relay
四邊狀態會保持一致。
三十四、切回 AUTO
Browser 按:
AUTO
ESP32:
MANUAL
↓
AUTO
並立即重新執行:
handleAutomaticControl();
例如此時:
Temperature = 25°C
即使 Relay 原本被手動開啟:
Relay ON
回到 AUTO 後:
Relay OFF
三十五、MQTT 遠端控制 Relay
使用:
mosquitto_pub \
-h 192.168.1.100 \
-t esp32/environment/relay/set \
-m ON
ESP32 收到:
Topic:
esp32/environment/relay/set
Payload:
ON
執行:
MANUAL
↓
Relay ON
關閉:
mosquitto_pub \
-h 192.168.1.100 \
-t esp32/environment/relay/set \
-m OFF
三十六、MQTT 切換 AUTO 模式
mosquitto_pub \
-h 192.168.1.100 \
-t esp32/environment/mode/set \
-m AUTO
手動模式:
mosquitto_pub \
-h 192.168.1.100 \
-t esp32/environment/mode/set \
-m MANUAL
三十七、監看 MQTT JSON
Windows / Linux / Raspberry Pi:
mosquitto_sub \
-h 192.168.1.100 \
-t esp32/environment/status \
-v
可能收到:
{
"device": "ESP32-ENV-01",
"temperature": 27.3,
"humidity": 62.8,
"light": 45.6,
"ldr_raw": 1867,
"relay": false,
"led": false,
"alarm": false,
"mode": "AUTO",
"wifi_rssi": -49,
"mqtt": true,
"firmware": "1.0.0"
}
三十八、Availability 與 Last Will
MQTT 另外 Publish:
esp32/environment/availability
正常:
online
如果 ESP32:
斷電
Wi-Fi 中斷
當機
Broker 可以利用 MQTT Last Will:
offline
通知其他 Client。
這對 IoT Dashboard 很重要。
因為:
沒有收到新溫度
並不一定代表:
Temperature 沒變
也可能代表:
ESP32 已 Offline
三十九、IoT Dashboard 可以怎麼做?
MQTT Server 可以接:
Node-RED
流程:
MQTT In
↓
JSON
↓
Dashboard
例如:
Temperature Gauge
Humidity Gauge
Light Gauge
Relay Switch
Alarm Indicator
Online Indicator
形成:
ESP32
↓
MQTT
↓
Mosquitto
↓
Node-RED
↓
Dashboard
四十、也可以接 Home Assistant
Topic:
esp32/environment/status
可以進一步整合:
Home Assistant
控制:
Relay
顯示:
Temperature
Humidity
Light
甚至建立 Automation:
Temperature > 32°C
↓
手機通知
四十一、也可以存進 Database
完整架構:
ESP32
↓
MQTT
↓
Mosquitto
↓
Node-RED / Python
↓
MySQL
資料表例如:
environment_log
欄位:
id
device_id
temperature
humidity
light
relay
alarm
created_at
就可以保存:
Sensor Historical Data。
四十二、進一步加入 Grafana
ESP32
↓
MQTT
↓
Database
↓
Grafana
Dashboard 顯示:
24 小時溫度曲線
24 小時濕度曲線
光線變化
Relay ON 時間
Alarm 次數
這才真正進入:
IoT Monitoring Platform。
四十三、OTA 如何整合進來?
本章 Firmware 中:
ArduinoOTA.begin();
並在:
loop()
持續:
ArduinoOTA.handle();
目前 Espressif 官方 ArduinoOTA 範例同樣採用 ArduinoOTA.begin() + ArduinoOTA.handle(),並支援 Hostname、Password、Start / End / Progress / Error Callback。
因此第一次使用 USB Upload 後:
Firmware 1.0.0
之後就可以:
Wi-Fi OTA
↓
1.0.1
↓
1.1.0
↓
2.0.0
不用再拆線接 USB。
四十四、如何測試 OTA?
先使用 USB 上傳:
Firmware 1.0.0
確認 Serial:
ArduinoOTA Ready
OTA Hostname:
esp32-env-01
接著修改:
const char* FIRMWARE_VERSION =
"1.1.0";
然後 Arduino IDE:
Tools
↓
Port
↓
esp32-env-01
透過 Network Port:
Upload
完成 OTA。
Web Dashboard 之後就會看到:
Firmware: 1.1.0
四十五、OTA 開始時為什麼 Relay OFF?
本章:
ArduinoOTA.onStart(
[]() {
setRelay(false);
setAlarm(false);
}
);
代表 Firmware Update 開始:
Relay OFF
Buzzer OFF
避免更新期間 Relay 狀態失去軟體控制。
但這只是:
教學預設 Safe State。
真正產品如果 Relay 控制:
- 冷凍機
- Pump
- Heater
- 工業設備
- 安全系統
必須依產品 Risk Assessment 定義 OTA Safe State,不能全部一律關閉。
四十六、本章為什麼完全避免長 delay()?
因為系統同時需要:
Web
MQTT
OTA
Button
Sensor
LCD
Wi-Fi
如果寫:
delay(
10000
);
這 10 秒:
Web 無法及時回應
MQTT loop 停止
OTA 不處理
Button 無法即時處理
所以最後的整合專題必須進一步從:
Sequential Beginner Programming
升級為:
Event / Timer Driven Programming。
四十七、millis() 排程概念
例如 Sensor:
if (
millis() -
lastSensorMillis >=
2500
) {
readSensors();
}
LCD:
if (
millis() -
lastLCDMillis >=
1000
) {
updateLCD();
}
MQTT:
if (
millis() -
lastMQTTPublishMillis >=
5000
) {
publishMQTTStatus();
}
三個功能互不阻塞。
四十八、Button Debounce
Mechanical Button 按一下不一定只有:
LOW
一次。
可能實際:
LOW
HIGH
LOW
HIGH
LOW
在幾毫秒內抖動。
因此程式使用:
50 ms
Debounce:
const unsigned long
BUTTON_DEBOUNCE = 50;
避免 Relay 一按就:
ON
OFF
ON
OFF
快速切換。
四十九、LCD 顯示設計
第一行:
T:26.4 H:63.2
第二行:
L:045 R:ON A
其中:
045
=
45% Light
R:ON
=
Relay ON
A
=
AUTO
如果:
M
代表:
MANUAL
五十、Web API 也可以被 App 使用
這套系統的:
/api/status
不是只有 Browser JavaScript 能用。
手機 App 也可以:
GET /api/status
得到:
{
"temperature": 26.5,
"humidity": 61.3,
"light": 55.1
}
因此之後如果要做:
iPhone App
Android App
Flutter App
Python Program
都可以直接使用相同 API。
五十一、Web Control API
Relay:
GET /relay/on
GET /relay/off
模式:
GET /mode/auto
GET /mode/manual
所以:
Browser
App
Python
都能控制 ESP32。
五十二、正式 API 不建議用 GET 改變狀態
本章為了讓 Arduino 入門教材容易理解,使用:
GET /relay/on
但正式 REST API 比較合理的做法是:
POST /api/relay
Payload:
{
"state": true
}
或:
PUT /api/device/state
因為:
GET 原則上應該用於取得資料,而不是改變系統狀態。
這是從 Maker 走向 Web API 設計時值得修正的部分。
五十三、Web Server 安全問題
本章 Web Dashboard:
http://ESP32-IP
沒有完整 Authentication。
因此用途應限定:
教材/可信任 LAN。
不要直接:
Internet
↓
Port Forward 80
↓
ESP32
因為任何能連到 ESP32 的使用者都可能:
Relay ON
Relay OFF
五十四、產品版 Web Security
正式產品應考慮:
HTTPS
Authentication
Session
CSRF Protection
API Token
VPN
Firewall
IoT VLAN
如果 ESP32 只需要 IoT Server 遠端控制,也可以:
禁止 Internet 直接連 ESP32
全部經由:
MQTT Broker
集中控制。
五十五、MQTT 也不應直接裸跑 Internet
本章:
MQTT Port 1883
適合:
LAN 教學。
正式產品應優先:
MQTTS
例如:
8883
並加入:
TLS
Server Certificate Validation
Username / Password
Client Certificate
Espressif 現行 ESP-MQTT 官方實作支援 MQTT over TLS、WebSocket Secure 與多種 Authentication 架構。
五十六、IoT 系統的三層控制
這個專題其實已經具備三層控制。
第一層:Local Automatic
Sensor
↓
ESP32
↓
Relay
不需要 Internet。
第二層:Local Manual
Button
↓
ESP32
或:
LAN Browser
↓
ESP32
第三層:Remote IoT
IoT Server
↓
MQTT
↓
ESP32
這種設計非常重要。
因為 IoT 不應該變成:
Internet 斷掉,設備就完全不能用。
五十七、系統 Offline 時應該怎麼工作?
假設 Router 壞掉。
ESP32:
Wi-Fi Offline
但是:
DHT22
LDR
LCD
Relay
Buzzer
Button
仍然繼續工作。
也就是:
Internet
X
Local Control
✓
這是比單純 Cloud Device 更可靠的架構。
五十八、MQTT Offline 又如何?
假設:
Wi-Fi OK
MQTT Broker Down
Web:
仍然可用
Auto Control:
仍然可用
LCD:
仍然可用
Button:
仍然可用
只有:
MQTT Remote Control
暫時不可用。
程式每:
5 秒
重新嘗試 MQTT。
五十九、為什麼 MQTT Reconnect 不能一直 while?
很多簡單範例:
while (
!mqttClient.connected()
) {
connectMQTT();
}
如果 Broker Offline:
ESP32
↓
一直卡在 while
結果:
Web 卡住
Button 卡住
OTA 卡住
所以本章使用:
每 5 秒嘗試一次
而不是:
無限 Blocking Retry
六十、Wi-Fi Reconnect 也是相同概念
如果 Router 暫時消失:
Wi-Fi Offline
ESP32 不應該:
while forever
而是:
Local Control 繼續
+
每 10 秒重新 Wi-Fi Connect
這是一種:
Graceful Degradation。
六十一、PubSubClient Buffer 為什麼設 512?
目前 PubSubClient 預設 Buffer Size 是:
256 bytes
並提供:
setBufferSize()
調整。
本章 JSON 有多個欄位:
temperature
humidity
light
relay
alarm
mode
firmware
因此設定:
mqttClient.setBufferSize(
512
);
避免 JSON 擴充後太接近預設限制。
六十二、為什麼每台 MQTT Client ID 要不同?
錯誤:
ESP32 #1
Client ID = ESP32
ESP32 #2
Client ID = ESP32
Broker 可能將舊 Client 踢掉。
因此本章使用:
ESP32-ENV-
+
MAC Address
例如:
ESP32-ENV-246F28123456
就能避免不同 ESP32 使用相同 Client ID。
六十三、Firmware Version 也放進 JSON
本章:
"firmware": "1.0.0"
因此 IoT Server 可以知道:
Device 1
→ 1.0.0
Device 2
→ 1.1.0
Device 3
→ 0.9.5
未來就可以建立:
Firmware Management Dashboard。
六十四、進一步 OTA Management
例如 Server 保存:
Latest Firmware:
1.2.0
ESP32:
Current:
1.0.0
Dashboard:
Update Required
最後:
IoT Server
↓
OTA Command
↓
ESP32
↓
Firmware Download
↓
1.2.0
這就把:
第 18 章 OTA
正式整合到 IoT Product 架構。
六十五、本章還可以加入 ESP-NOW Sensor Node
第 16 章學過 ESP-NOW。
現在可以把主 ESP32 升級成:
Gateway。
例如:
ESP32 Sensor Node #1
DHT22
│
│ ESP-NOW
▼
ESP32 Main Controller
│
├── LCD
├── Relay
├── Web
└── MQTT
再增加:
Node #2
Soil Sensor
Node #3
Outdoor Temperature
Node #4
Door Sensor
架構:
Node1 ──┐
Node2 ──┤
Node3 ──┼── ESP-NOW ──→ Gateway
Node4 ──┘ │
▼
MQTT
六十六、也可以加入 Deep Sleep Sensor
遠端 Node:
Battery
↓
ESP32
↓
Wake Up
↓
Sensor
↓
ESP-NOW
↓
Deep Sleep
主機:
ESP32 Gateway
↓
MQTT
↓
Server
這樣:
Sensor Node
=
低功耗
Gateway
=
24 小時運作
就是非常實用的 IoT 架構。
六十七、也可以加入 ESP32-CAM
第 19 章 Camera:
ESP32-CAM
↓
PIR
↓
Motion
↓
JPEG
可以 Publish:
esp32/camera/motion
主控制器:
ESP32 Environment
管理:
Temperature
Humidity
Light
Camera:
ESP32-CAM
管理:
Image
Motion
Server 將兩邊整合:
IoT Server
/ \
/ \
Environment Camera
ESP32 ESP32-CAM
六十八、整套 ESP32 IoT 最終架構
把 20 章全部串起來,可以形成:
Battery Sensor Nodes
│
│ ESP-NOW
▼
┌─────────────────┐
│ ESP32 Gateway │
│ │
│ DHT22 │
│ LDR │
│ LCD1602 │
│ Relay │
│ Buzzer │
│ LED │
│ Button │
└────────┬────────┘
│
│ Wi-Fi
┌───────┴──────────┐
│ │
▼ ▼
Web Dashboard MQTT
│
▼
IoT Server
│
┌─────────┼──────────┐
│ │ │
▼ ▼ ▼
Database Dashboard OTA
│
▼
Firmware
另外:
ESP32-CAM
│
├── PIR
├── JPEG
└── Wi-Fi
│
▼
IoT Server
這已經是一個完整:
ESP32 IoT Ecosystem。
六十九、IoT Dashboard 可以再加入哪些功能?
可以增加:
- 24 小時 Temperature Chart
- Humidity Chart
- Light Chart
- Relay Runtime
- Alarm History
- Online / Offline
- RSSI
- Last Seen
- Firmware Version
- OTA Status
- Device Uptime
- Sensor Error Count
- Manual Operation Log
例如:
ESP32-ENV-01
Online ✓
Firmware 1.2.0
Temperature 26.3°C
Humidity 62.1%
Light 45%
Relay OFF
Alarm NORMAL
Mode AUTO
RSSI -49 dBm
七十、加入資料記錄後可以做什麼?
Database 可以產生:
Temperature
30 ┤
28 ┤ ╭───╮
26 ┤───────╯ ╰────
24 ┤
└────────────────
Time
接著就能分析:
- 每日最高溫
- 每日最低溫
- 平均濕度
- 夜間光線
- Relay 每天工作幾小時
- 警報發生次數
- Sensor 異常
ESP32 就從:
Controller
升級成:
Data Acquisition Node。
七十一、進階:加入 NTP
可以讓 ESP32取得真正時間:
Wi-Fi
↓
NTP
↓
Date / Time
JSON:
{
"timestamp": "2026-08-21T09:50:00+08:00",
"temperature": 26.3
}
如此 Server 記錄會更完整。
七十二、進階:加入 RTC DS3231
如果 Internet 無法連線,也可以:
DS3231
↓
ESP32
取得時間。
這適合:
- Logger
- Offline System
- Industrial Controller
七十三、進階:設定值由 Web 修改
目前 Threshold 寫死:
RELAY_TEMP_ON = 30.0;
未來可以 Web 設定:
Relay ON Temperature:
[ 30.0 ]
Relay OFF Temperature:
[ 28.0 ]
Alarm:
[ 32.0 ]
送到 ESP32:
{
"relay_on": 30,
"relay_off": 28,
"alarm": 32
}
七十四、設定值應該存到 NVS
如果使用者 Web 改:
30°C
↓
35°C
重開機後不應該又回:
30°C
所以可以使用:
Preferences
保存:
Relay Threshold
Alarm Threshold
Control Mode
Device Name
MQTT Server
到 ESP32 NVS。
七十五、進階:Wi-Fi Provisioning
現在程式:
const char* WIFI_SSID =
"YOUR_WIFI_SSID";
產品不能每賣一台都重新 Compile。
更合理:
第一次開機
↓
ESP32 SoftAP
↓
手機 Connect
↓
輸入 Wi-Fi
↓
Save NVS
↓
Restart
↓
Connect Router
這就是:
Wi-Fi Provisioning。
七十六、從 Maker 走向 Product 還缺哪些能力?
這個第 20 章專題已經很完整。
但正式量產產品還需要:
Provisioning
TLS
Authentication
Watchdog
Brownout Handling
NVS Configuration
Signed OTA
Secure Boot
Flash Encryption
Logging
Factory Reset
Device ID
Manufacturing Test
Error Recovery
也就是:
Prototype
↓
Stable Prototype
↓
Engineering Validation
↓
Product
仍然有一段工程化過程。
七十七、完整測試順序
不要一開始全部一起測。
建議:
- ESP32 + DHT22;確認:;Temperature Humidity
- 加入:;LDR;確認:;ADC Raw Light %
- 加入:;LCD1602
- 加入:;Relay LED Buzzer Button;先離線測 Auto / Manual。
- 加入:;Wi-Fi
- 測:;Web Dashboard
- 加入:;MQTT
- 最後測:;OTA;這樣最容易除錯。
七十八、DHT22 顯示 ERROR 怎麼辦?
如果:
DHT22 Read Failed
檢查:
- DATA 是否 GPIO4
- VCC
- GND
- Pull-up
- DHT Library
- 讀取間隔
- Sensor 是否故障
DHT22 不應該用:
每 10 ms
高速讀取。
本章:
2.5 秒
讀一次較合理。
七十九、LDR 一直 0 怎麼辦?
檢查:
3.3V
LDR
10kΩ
GPIO34
GND
使用 Serial:
LDR Raw
觀察。
遮住:
數值應變化
手電筒照:
數值應變化
如果完全不變:
可能是:
- Voltage Divider 接錯
- GPIO 接錯
- GND 沒共地
八十、Light % 顛倒怎麼辦?
如果你的 Voltage Divider 接法是:
3.3V
↓
10kΩ
↓
GPIO34
↓
LDR
↓
GND
則可能:
越亮
→ ADC 越低
這時改成:
lightPercent =
100.0 -
(
ldrRaw /
4095.0 *
100.0
);
即可。
八十一、LCD 沒有顯示
先跑:
I²C Scanner。
如果找到:
0x27
使用:
LiquidCrystal_I2C lcd(
0x27,
16,
2
);
如果:
0x3F
改:
LiquidCrystal_I2C lcd(
0x3F,
16,
2
);
八十二、Relay 啟動時突然跳一下
Relay Boot Glitch 是實際設備很重要的問題。
原因可能包括:
- GPIO Boot State
- Relay Active LOW
- Module Input Floating
- Startup 初始化時間
因此:
pinMode(
RELAY_PIN,
OUTPUT
);
setRelay(
false
);
應該儘早執行。
正式硬體也可以加入:
Pull-up / Pull-down
Transistor Driver
Hardware Enable
確保開機狀態安全。
八十三、MQTT 一直連不上
檢查:
MQTT_HOST
MQTT_PORT
Username
Password
Firewall
Mosquitto Listener
一般 LAN Mosquitto:
1883
TLS:
8883
不要把代表本機回環介面的位址填入 ESP32 的 MQTT Broker 設定。
對 ESP32 而言,回環位址只代表 ESP32 自己;應填入 Broker 在區域網路中的實際 IP Address。
八十四、Web 可以用但 MQTT 不行
這代表:
Wi-Fi
✓
Web Server
✓
但:
MQTT Broker
X
檢查 Broker Server。
例如:
mosquitto_sub -t '#'
先在 Server 本機測。
八十五、MQTT 可以用但 Web 打不開
Serial 查看:
IP:
192.168.1.120
Browser:
http://192.168.1.120/
不要使用:
https://
因為本章 Web Server 是:
HTTP
不是 HTTPS。
八十六、OTA 看不到 Network Port
確認:
ArduinoOTA Ready
以及 PC 與 ESP32:
位於可互相通訊的 LAN
同時檢查:
- Windows Firewall
- VPN
- AP Isolation
- mDNS
- Wi-Fi
ArduinoOTA 官方實作目前透過 Wi-Fi 網路及 mDNS 宣告讓 Arduino IDE 發現裝置。
八十七、為什麼這個專題比單純 IoT Sensor 更完整?
一般 IoT Sensor:
Sensor
↓
Wi-Fi
↓
Cloud
如果 Cloud 掛掉:
整台設備幾乎沒功能
本章:
Sensor
↓
ESP32
↓
Local Automatic Control
↓
Local Button
↓
LCD
↓
Web
↓
MQTT
所以:
Cloud 是功能延伸
而不是:
所有基本功能都依賴 Cloud
這是更合理的 Embedded IoT 架構。
八十八、這套專題適合改成哪些產品?
智慧機房監控
DHT22
↓
Temperature Alarm
↓
Fan Relay
↓
MQTT
智慧倉庫
Temperature
Humidity
Light
↓
Dashboard
溫室環境控制
將 Relay 改成:
Fan
Pump
Grow Light
智慧家庭
Temperature
Light
↓
Fan
Light
↓
Web / MQTT
電子設備箱監控
Temperature
↓
Cooling Fan
↓
Alarm
小型 Server Room
Environment
↓
MQTT
↓
Dashboard
↓
Alarm Notification
八十九、進階版可以加入更多 Sensor
例如:
BME280
BMP280
BH1750
MQ-2
CO2 Sensor
Soil Moisture
Water Level
PIR
Door Sensor
Current Sensor
Voltage Sensor
ESP32:
I²C
SPI
UART
ADC
GPIO
都有足夠能力整合。
九十、ESP32 20 章最後真正學到什麼?
一路從最基本:
ESP32 是什麼?
開始。
逐步進入:
GPIO
↓
Digital Input
↓
ADC
↓
PWM
↓
Sensor
↓
I²C
↓
SPI
↓
UART
↓
Wi-Fi
↓
Web Server
↓
BLE
↓
MQTT
↓
ESP-NOW
↓
Deep Sleep
↓
OTA
↓
Camera
↓
Integrated IoT System
最後得到的不只是:
20 個獨立範例。
而是建立一套完整:
ESP32 Embedded + IoT 開發能力。
九十一、本章完整系統資料流
Sensor:
DHT22
│
├── Temperature
└── Humidity
LDR
│
└── Light
Button
│
└── Manual Command
進入:
ESP32
ESP32 執行:
Sensor Processing
↓
Automatic Logic
↓
Control Mode
↓
Output
輸出:
LCD
Relay
LED
Buzzer
另外:
ESP32
↓
Wi-Fi
↓
Web Server
以及:
ESP32
↓
MQTT
↓
IoT Server
維護:
Arduino IDE
↓
OTA
↓
ESP32 Firmware
九十二、最終完整架構
┌───────────┐
│ DHT22 │
└─────┬─────┘
│
┌─────▼─────┐
│ Temperature│
│ Humidity │
└─────┬─────┘
│
┌─────────┐ │
│ LDR ├──────────┤
└─────────┘ │
▼
┌─────────────┐
┌─────────┐ │ │
│ Button ├──►│ ESP32 │
└─────────┘ │ │
└──────┬──────┘
│
┌─────────────────┼──────────────────┐
│ │ │
▼ ▼ ▼
LCD1602 Relay Buzzer
│
└──────────────► LED
│
│ Wi-Fi
▼
┌─────────────┐
│ Web Server │
└──────┬──────┘
│
┌───────────┼───────────┐
│ │ │
▼ ▼ ▼
Sensor Relay Status
Data Control
│
▼
MQTT
│
▼
┌─────────────┐
│ IoT Server │
└──────┬──────┘
│
┌─────────────┼─────────────┐
│ │ │
▼ ▼ ▼
Database Dashboard OTA
九十三、本章學習重點整理
完成第 20 章後,應該掌握以下能力。
ESP32
作為整套智慧控制系統核心。
DHT22
取得:
Temperature
Humidity
LDR
使用:
ADC1 GPIO34
取得相對光線。
LCD1602
透過:
I²C
建立本機 HMI。
Relay
控制:
Fan / Load
Buzzer
建立:
High Temperature Alarm
LED
建立:
Automatic Night Light
Button
提供:
Local Manual Override
Wi-Fi
連接:
LAN / IoT Network
Web Server
提供:
Browser Dashboard
JSON
統一系統狀態資料格式。
MQTT
完成:
Publish
Subscribe
Remote Control
IoT Server
AUTO / MANUAL
建立真正設備控制邏輯。
Non-blocking
讓:
Web
MQTT
OTA
Sensor
Button
LCD
同時運作。
OTA
完成:
Firmware Remote Update
九十四、本章實作成果
我們最後完成的是:
ESP32 智慧環境監控與遠端控制系統
具備:
DHT22
+
LDR
+
LCD1602
+
Relay
+
Buzzer
+
LED
+
Button
+
Wi-Fi
+
Web Server
+
JSON
+
MQTT
+
Automatic Control
+
Manual Control
+
OTA
這已經非常接近一個完整:
ESP32 IoT Controller Prototype。
從這裡開始,可以繼續往:
PCB
Enclosure
Power Supply
Security
Database
Cloud
Mobile App
OTA Platform
Production Test
發展成真正產品。