📑 เนื้อหาในบทความ
🏠 ภาพรวม Smart Home ด้วย ESP32 + Node-RED
การผสมผสาน ESP32, Node-RED พร้อม Dashboard 2.0 ใหม่ และ Home Assistant จะช่วยให้คุณสร้างระบบ Smart Home ที่:
- Local-First: ทำงานได้โดยไม่ต้องพึ่งพา Internet (ยกเว้น Remote Access)
- Real-Time: ตอบสนองทันทีด้วย MQTT Protocol
- Flexible: ปรับแต่ง UI ได้อย่างอิสระด้วย Dashboard 2.0
- Scalable: เพิ่ม Sensor/Device ได้ไม่จำกัด
- Automated: สร้าง Automation ซับซ้อนด้วย Node-RED
💡 Node-RED Dashboard 2.0 คืออะไร? เป็นเวอร์ชันใหม่ล่าสุดของ Node-RED Dashboard ที่มาพร้อมกับ UI ที่ทันสมัยขึ้น ประสิทธิภาพดีขึ้น และรองรับ Theme และ Layout ที่ยืดหยุ่นกว่าเดิม
📋 ข้อกำหนดเบื้องต้น
Hardware ที่ต้องใช้:
- ESP32 Board (ESP32 DevKit, NodeMCU-32, หรือตระกูล ESP32 อื่นๆ) - 1 ตัวขึ้นไป
- Sensors (DHT11/DHT22, BMP280, หรืออื่นๆ) - ตามต้องการ
- Raspberry Pi 4 (แนะนำ 4GB+) หรือ Computer สำหรับรัน Node-RED
- Relay Module (ถ้าต้องการควบคุมไฟ/อุปกรณ์)
Software ที่ต้องใช้:
- Arduino IDE พร้อม ESP32 Board Support
- Node.js (สำหรับ Node-RED)
- MQTT Broker (Mosquitto, EMQX, หรือใช้ Home Assistant built-in)
- Home Assistant (ตัวเลือก - แนะนำ)
ระดับความยาก:
🏗️ สถาปัตยกรรมระบบ
ก่อนเริ่ม มาทำความเข้าใจโฟลว์ข้อมูลกันก่อน:
ESP32 (MQTT Publisher)
↓ (Sensor Data / Commands)
MQTT Broker (Mosquitto / Home Assistant)
↓ (Subscribe / Publish)
Node-RED (Logic Processing + Dashboard 2.0)
↓ (MQTT Discovery / API)
Home Assistant (Automation + Integration)
หน้าที่ของแต่ละส่วน:
- ESP32: อ่านค่า Sensor และส่งข้อมูลผ่าน MQTT รับคำสั่งควบคุม Relay
- MQTT Broker: กลางเป็นตัวกลางในการส่งข้อมูลระหว่าง Devices
- Node-RED: ประมวลผลข้อมูล สร้าง Logic และแสดงผลบน Dashboard 2.0
- Home Assistant: รวบรวมทุกอย่างไว้ในที่เดียว สร้าง Automation ซับซ้อน
📡 ESP32: MQTT Client เพื่อส่งข้อมูล Sensor
เริ่มต้นด้วยการเขียนโค้ด ESP32 ให้เชื่อมต่อ WiFi และ MQTT Broker แล้วส่งข้อมูล Sensor
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// ===== WiFi Configuration =====
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
// ===== MQTT Configuration =====
const char* mqtt_server = "192.168.1.100"; // IP ของ MQTT Broker (Raspberry Pi)
const int mqtt_port = 1883;
const char* mqtt_user = "homeassistant"; // ถ้ามี
const char* mqtt_password = "your_password"; // ถ้ามี
// ===== Sensor Configuration =====
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// ===== Topics =====
const char* temp_topic = "home/sensor/temperature";
const char* hum_topic = "home/sensor/humidity";
// ===== Objects =====
WiFiClient espClient;
PubSubClient client(espClient);
// ===== ตัวแปร =====
unsigned long lastMsg = 0;
const long interval = 5000; // ส่งข้อมูลทุก 5 วินาที
void setup() {
Serial.begin(115200);
dht.begin();
// เชื่อมต่อ WiFi
setup_wifi();
// ตั้งค่า MQTT
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
// ===== Callback: รับคำสั่งจาก MQTT =====
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("]: ");
String messageTemp;
for (int i = 0; i < length; i++) {
messageTemp += (char)message[i];
}
Serial.println(messageTemp);
// ตัวอย่าง: ควบคุม Relay ถ้าได้รับคำสั่ง
if (String(topic) == "home/relay/command") {
if (messageTemp == "ON") {
digitalWrite(RELAY_PIN, HIGH);
Serial.println("Relay turned ON");
} else if (messageTemp == "OFF") {
digitalWrite(RELAY_PIN, LOW);
Serial.println("Relay turned OFF");
}
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// สร้าง Client ID แบบสุ่ม
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
Serial.println("connected");
// Subscribe หัวข้อที่ต้องการรับคำสั่ง
client.subscribe("home/relay/command");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" retrying in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// ===== ส่งข้อมูล Sensor ทุก 5 วินาที =====
unsigned long now = millis();
if (now - lastMsg > interval) {
lastMsg = now;
// อ่านค่าอุณหภูมิและความชื้น
float temp = dht.readTemperature();
float hum = dht.readHumidity();
// ตรวจสอบว่าอ่านค่าได้หรือไม่
if (isnan(temp) || isnan(hum)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// แปลงค่าเป็น String
char tempStr[8];
char humStr[8];
dtostrf(temp, 1, 2, tempStr);
dtostrf(hum, 1, 2, humStr);
// ส่งข้อมูลผ่าน MQTT
client.publish(temp_topic, tempStr);
client.publish(hum_topic, humStr);
Serial.print("Temperature: ");
Serial.print(temp);
Serial.print("°C | Humidity: ");
Serial.print(hum);
Serial.println("%");
}
}⚠️ หมายเหตุ: อย่าลืมติดตั้ง Library PubSubClient และ DHT ผ่าน Arduino IDE Library Manager ก่อน
🚀 ติดตั้ง Node-RED พร้อม Dashboard 2.0
บน Raspberry Pi (แนะนำ):
# อัปเดตระบบ
sudo apt update && sudo apt upgrade -y
# ติดตั้ง Node.js (เวอร์ชัน LTS)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs
# ติดตั้ง Node-RED
sudo npm install -g --unsafe-perm node-red
# ติดตั้ง Dashboard 2.0
cd ~/.node-red
npm install @node-red/dashboard
# เริ่ม Node-RED
node-redเข้าถึง Node-RED Editor:
- เปิด Web Browser ไปที่:
http://<RASPBERRY_PI_IP>:1880 - คุณจะเห็น Node-RED Editor พร้อมใช้งาน
💡 เคล็ดลับ: ตั้งค่าให้ Node-RED เริ่มทำงานอัตโนมัติเมื่อบู๊ตด้วย sudo systemctl enable node-red
🎨 สร้าง Dashboard 2.0 สำหรับ ESP32 Sensor
ตอนนี้สร้าง Flow ใน Node-RED เพื่อรับข้อมูลจาก ESP32 และแสดงผลบน Dashboard 2.0
Flow ที่ต้องสร้าง:
- MQTT In Node: Subscribe หัวข้อ
home/sensor/temperature - Function Node: แปลงข้อมูล (ถ้าต้องการ)
- Chart Node: แสดงกราฟอุณหภูมิแบบ Real-time
- Gauge Node: แสดงค่าปัจจุบันเป็นเข็มวัด
ตัวอย่าง Flow JSON (Import ได้เลย):
[
{
"id": "mqtt-in-temp",
"type": "mqtt in",
"z": "d89c6f8.b23859",
"name": "",
"topic": "home/sensor/temperature",
"qos": "0",
"datatype": "auto",
"broker": "mqtt-broker",
"nl": false,
"rap": true,
"rh": 0,
"inputs": 0,
"x": 140,
"y": 100,
"wires": [["chart-temp", "gauge-temp"]]
},
{
"id": "chart-temp",
"type": "ui-chart",
"z": "d89c6f8.b23859",
"name": "Temperature",
"group": "sensors-group",
"order": 1,
"width": "12",
"height": "6",
"label": "อุณหภูมิ (°C)",
"chartType": "line",
"legend": "false",
"xformat": "HH:mm:ss",
"interpolate": true,
"nodata": "",
"dot": true,
"ymin": "",
"ymax": "",
"removeOlder": "1",
"removeOlderUnit": "3600",
"cutout": 0,
"useOneColor": false,
"colors": ["#1f77b4", "#aec7e8", "#ff7f0e", "#2ca02c", "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5"],
"useOldStyle": false,
"outputs": 1,
"x": 450,
"y": 100,
"wires": [[]]
},
{
"id": "gauge-temp",
"type": "ui-gauge",
"z": "d89c6f8.b23859",
"name": "",
"group": "sensors-group",
"order": 2,
"width": "6",
"height": "4",
"name": "",
"label": "อุณหภูมิ",
"format": "°C",
"min": "0",
"max": "50",
"colors": ["#00b500", "#e6e600", "#ca3838"],
"seg1": "",
"seg2": "",
"diff": false,
"className": "",
"x": 450,
"y": 180,
"wires": [[]]
},
{
"id": "mqtt-broker",
"type": "mqtt-broker",
"name": "Local MQTT",
"broker": "192.168.1.100",
"port": "1883",
"clientid": "",
"autoConnect": true,
"usetls": false,
"protocolVersion": "4",
"keepalive": "60",
"cleansession": true,
"birthTopic": "",
"birthQos": "0",
"birthPayload": "",
"birthMsg": {},
"closeTopic": "",
"closeQos": "0",
"closePayload": "",
"closeMsg": {},
"willTopic": "",
"willQos": "0",
"willPayload": "",
"willMsg": {},
"sessionExpiry": ""
},
{
"id": "sensors-group",
"type": "ui-group",
"name": "Sensors",
"page": "",
"width": "12",
"height": "1",
"order": 1
}
]เข้าถึง Dashboard:
- เปิด Web Browser ไปที่:
http://<RASPBERRY_PI_IP>:1880/ui - คุณจะเห็น Dashboard พร้อมกราฟและเข็มวัด!
🎨 Dashboard 2.0 Features: ปรับแต่ง Layout ได้อิสระกว่าเดิม รองรับ Grid Layout, Tabs, และ Theme สวยงาม
🏠 เชื่อมต่อกับ Home Assistant
หลังจากมี Node-RED แล้ว เชื่อมต่อกับ Home Assistant เพื่อรวบรวมทุกอย่างไว้ในที่เดียว
วิธีที่ 1: ผ่าน MQTT (แนะนำ):
Home Assistant มี MQTT Integration ในตัว ให้เพิ่ม Sensor ผ่าน configuration.yaml
# configuration.yaml
# MQTT Sensor สำหรับอุณหภูมิ
mqtt:
sensor:
- name: "ESP32 Temperature"
state_topic: "home/sensor/temperature"
unit_of_measurement: "°C"
device_class: temperature
- name: "ESP32 Humidity"
state_topic: "home/sensor/humidity"
unit_of_measurement: "%"
device_class: humidityวิธีที่ 2: ผ่าน Node-RED API:
ใช้ Node-RED เพื่อส่งข้อมูลไป Home Assistant ผ่าน REST API
// ใน Function Node ของ Node-RED
msg.headers = {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_LONG_LIVED_ACCESS_TOKEN"
};
msg.payload = {
"state": msg.payload,
"attributes": {
"unit_of_measurement": "°C",
"friendly_name": "ESP32 Temperature"
}
};
return msg;
// แล้วต่อกับ HTTP Request Node ไปที่:
// POST http://<HOME_ASSISTANT_IP>:8123/api/states/sensor.esp32_temperature💡 เคล็ดลับ: ใช้ Node-RED กับ Home Assistant จะช่วยให้สร้าง Automation ที่ซับซ้อนได้ง่ายขึ้น เช่น การตั้งเวลา, Logic แบบ Multi-Condition
⚡ เทคนิคขั้นสูง
1. ใช้ ESP32 เป็น MQTT + WiFi + Relay Controller:
เพิ่ม Relay ลงใน ESP32 เพื่อควบคุมไฟ/อุปกรณ์ และรับคำสั่งผ่าน MQTT
2. Dashboard 2.0 Layout Tips:
- ใช้ Tabs เพื่อแยกหมวดหมู่ (Sensors, Controls, Automation)
- ใช้ Grid Layout ใน Dashboard 2.0 เพื่อจัดวาง Widget อย่างเป็นระเบียบ
- ใช้ Theme ปรับแต่งสีตามต้องการ
3. บันทึกข้อมูลลง Database:
ใช้ Node-RED บันทึกข้อมูลลง InfluxDB หรือ MySQL เพื่อวิเคราะห์ย้อนหลัง
4. Remote Access:
ใช้ Cloudflare Tunnel หรือ Tailscale เพื่อเข้าถึงระบบจากภายนอกบ้านอย่างปลอดภัย
🔧 แก้ปัญหาที่พบบ่อย
ESP32 เชื่อมต่อ WiFi ไม่ได้?
ตรวจสอบ SSID และ Password ให้ถูกต้อง และแน่ใจว่า ESP32 อยู่ในระยะสัญญาณ WiFi
MQTT Connection หลุดบ่อย?
เพิ่ม client.loop() ใน loop() และใช้ reconnect() เมื่อเชื่อมต่อหลุด
Node-RED Dashboard ไม่โหลด?
ตรวจสอบว่าติดตั้ง @node-red/dashboard แล้ว และ restart Node-RED
Home Assistant ไม่เห็น Sensor?
ตรวจสอบ MQTT Configuration ใน Home Assistant และแน่ใจว่า ESP32 ส่งข้อมูลไปยัง Topic ที่ถูกต้อง
🎉 สรุป
ในบทความนี้ คุณได้เรียนรู้วิธีสร้างระบบ Smart Home ที่สมบูรณ์ด้วย ESP32, Node-RED, Dashboard 2.0 และ Home Assistant ซึ่งรวมถึง:
- ESP32 เป็น MQTT Client ส่งข้อมูล Sensor
- Node-RED ประมวลผลและแสดงผลบน Dashboard 2.0
- Home Assistant รวบรวมทุกอย่างไว้ในที่เดียว
- ระบบทำงานได้แบบ Local-First และ Real-time
หวังว่าคุณจะสนุกกับการสร้าง Smart Home ของคุณเอง! 🏠✨