🚀 ทำไมต้องใช้ MQTT กับ ESP32?
MQTT (Message Queuing Telemetry Transport) เป็นโปรโตคอลที่เบาและรวดเร็ว ออกแบบมาสำหรับอุปกรณ์ IoT โดยเฉพาะ เมื่อรวมกับ ESP32 และ MicroPython คุณจะได้ระบบที่:
- ใช้พลังงานน้อย: MQTT ออกแบบมาให้มี Payload เล็ก ประหยัดแบนด์วิดท์
- รวดเร็ว: การสื่อสารแบบ Real-time ด้วย latency ต่ำ
- ง่ายต่อการใช้งาน: MicroPython ทำให้เขียนโค้ดได้ง่ายเหมือน Python
- ยืดหยุ่น: รองรับการเชื่อมต่อกับ Cloud Platform หลากหลาย
💡 เคล็ดลับ: MQTT ใช้รูปแบบ Publish/Subscribe ซึ่งแตกต่างจาก HTTP ทำให้เหมาะสำหรับการส่งข้อมูลจาก Sensor หลายตัวไปยังระบบเดียว
📦 สิ่งที่ต้องเตรียม
🛠️ Hardware
- ✓ESP32 Board: บอร์ด ESP32 任何型号 (DevKit, NodeMCU, ฯลฯ)
- ✓USB Cable: สาย USB สำหรับเชื่อมต่อกับคอมพิวเตอร์
- ✓WiFi Connection: เครือข่าย WiFi ที่เชื่อมต่ออินเทอร์เน็ตได้
💻 Software
- ✓Thonny IDE: ดาวน์โหลดที่นี่ (ฟรี ใช้งานง่าย)
- ✓MicroPython Firmware: เฟิร์มแวร์สำหรับ ESP32
- ✓MQTT Broker: ใช้บริการฟรี เช่น HiveMQ 或 Mosquitto
🐍 MicroPython คืออะไร?
MicroPython เป็นการพอร์ต Python 3 มาทำงานบนไมโครคอนโทรลเลอร์ ทำให้คุณสามารถเขียนโค้ด Python เพื่อควบคุม Hardware ได้โดยตรง โดยไม่ต้องใช้ C++ ที่ซับซ้อน
✅ ข้อดี
- • ง่ายต่อการเรียนรู้
- • เขียนและทดสอบได้รวดเร็ว
- • มี Library มากมาย
- • Interactive REPL
⚠️ ข้อจำกัด
- • ช้ากว่า C/C++
- • ใช้หน่วยความจำมากกว่า
- • ไม่เหมาะกับงาน Heavy Computing
📡 MQTT คืออะไร?
MQTT เป็นโปรโตคอล Messaging แบบ Publish/Subscribe ที่ออกแบบมาสำหรับอุปกรณ์ที่มีทรัพยากรจำกัด ทำงานบน TCP/IP และมีส่วนสำคัญ 3 ส่วน:
Publisher
ผู้ส่งข้อความ (เช่น Sensor)
Broker
ตัวกลางจัดการข้อความ
Subscriber
ผู้รับข้อความ (เช่น Server, App)
📝 Key Concepts:
- Topic: ชื่อสำหรับจัดหมวดหมู่ข้อความ (เช่น
sensor/temperature) - Message: ข้อมูลที่ส่ง (Payload สามารถเป็น Text, JSON, ฯลฯ)
- QoS: ระดับความเชื่อถือ (0, 1, 2)
⚙️ การติดตั้ง MicroPython บน ESP32
Step 1: ดาวน์โหลด Firmware
- ไปที่ MicroPython Download Page
- ดาวน์โหลดไฟล์ `.bin` ล่าสุด (เช่น
ESP32_GENERIC-20240602-v1.23.0.bin) - จดตำแหน่งที่บันทึกไฟล์ไว้
Step 2: ติดตั้ง Thonny IDE
- ดาวน์โหลด Thonny จาก thonny.org
- ติดตั้งและเปิดโปรแกรม Thonny
- เชื่อมต่อ ESP32 ด้วย USB Cable
- ไปที่
Tools → Options → Interpreter - เลือก
MicroPython (ESP32)และกด Install or Update MicroPython - เลือก Port ของ ESP32 และติดตั้ง Firmware
✅ สำเร็จ! เมื่อติดตั้งเสร็จ คุณจะเห็น >>> ใน Shell ซึ่งเป็น REPL ของ MicroPython
💻 เขียนโปรแกรม MQTT พื้นฐาน
ตัวอย่างที่ 1: เชื่อมต่อ MQTT Broker
# ESP32 MicroPython MQTT Basic Example
# ตัวอย่างการเชื่อมต่อ MQTT Broker
import network
import time
from umqtt.simple import MQTTClient
# ============ WiFi Configuration ============
WIFI_SSID = "your_wifi_ssid" # แก้ไขเป็น WiFi ของคุณ
WIFI_PASSWORD = "your_wifi_password" # แก้ไขเป็น Password ของคุณ
# ============ MQTT Configuration ============
MQTT_BROKER = "broker.hivemq.com" # ใช้ Broker ฟรี
MQTT_PORT = 1883
MQTT_CLIENT_ID = "esp32_client_" + str(time.ticks_ms())
MQTT_USER = "" # ถ้ามี Authentication
MQTT_PASSWORD = "" # ถ้ามี Authentication
# ============ WiFi Connection ============
def connect_wifi():
"""เชื่อมต่อ WiFi"""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to WiFi...')
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
# รอการเชื่อมต่อ (timeout 10 วินาที)
timeout = 10
while not wlan.isconnected() and timeout > 0:
print('.', end='')
time.sleep(1)
timeout -= 1
if wlan.isconnected():
print('\nWiFi connected! IP:', wlan.ifconfig()[0])
return True
else:
print('\nFailed to connect WiFi')
return False
# ============ MQTT Callbacks ============
def mqtt_callback(topic, msg):
"""ฟังก์ชันที่ทำงานเมื่อได้รับข้อความ"""
print(f"Received message:")
print(f" Topic: {topic.decode('utf-8')}")
print(f" Message: {msg.decode('utf-8')}")
# ============ Main Program ============
if __name__ == "__main__":
# เชื่อมต่อ WiFi
if connect_wifi():
# สร้าง MQTT Client
client = MQTTClient(
MQTT_CLIENT_ID,
MQTT_BROKER,
MQTT_PORT,
MQTT_USER,
MQTT_PASSWORD
)
# ตั้งค่า Callback
client.set_callback(mqtt_callback)
# เชื่อมต่อ MQTT Broker
print(f"Connecting to MQTT Broker: {MQTT_BROKER}")
client.connect()
print("MQTT connected!")
# Subscribe หัวข้อ
topic = b"esp32/test"
client.subscribe(topic)
print(f"Subscribed to: {topic.decode('utf-8')}")
# วนลูปรับข้อความ
print("Waiting for messages...")
while True:
try:
client.wait_msg() # รอรับข้อความ
except Exception as e:
print(f"Error: {e}")
client.disconnect()
time.sleep(5)
client.connect()
client.subscribe(topic)
คำอธิบายโค้ด:
- network: Library สำหรับเชื่อมต่อ WiFi
- umqtt.simple: Library MQTT แบบง่าย (Built-in)
- connect_wifi(): ฟังก์ชันเชื่อมต่อ WiFi พร้อม Timeout
- mqtt_callback: ฟังก์ชันที่ทำงานอัตโนมัติเมื่อได้รับข้อความ
- client.wait_msg(): บล็อกรอรับข้อความ
📤 การ Publish และ Subscribe
ตัวอย่างที่ 2: Publish ข้อมูล Sensor
# ESP32 MicroPython MQTT Publisher Example
# ส่งข้อมูลจำลอง Sensor ไปยัง MQTT Broker
import network
import time
import json
from umqtt.simple import MQTTClient
from machine import Pin
import dht
# ============ Configuration ============
WIFI_SSID = "your_wifi_ssid"
WIFI_PASSWORD = "your_wifi_password"
MQTT_BROKER = "broker.hivemq.com"
MQTT_PORT = 1883
MQTT_CLIENT_ID = "esp32_sensor_" + str(time.ticks_ms())
# ============ Sensor Setup ============
# ใช้ DHT22 Sensor (หรือ DHT11) ที่ขา GPIO 4
dht_sensor = dht.DHT22(Pin(4))
# ============ WiFi Connection ============
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to WiFi...')
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
timeout = 10
while not wlan.isconnected() and timeout > 0:
print('.', end='')
time.sleep(1)
timeout -= 1
if wlan.isconnected():
print('\nWiFi connected!')
return True
return False
# ============ Read Sensor ============
def read_sensor():
"""อ่านค่าจาก DHT22 Sensor"""
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temperature, humidity
except Exception as e:
print(f"Sensor error: {e}")
return None, None
# ============ Main Program ============
if __name__ == "__main__":
if connect_wifi():
# สร้าง MQTT Client
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, MQTT_PORT)
client.connect()
print("MQTT connected!")
# หัวข้อ Topic
topic_temp = b"sensor/temperature"
topic_humidity = b"sensor/humidity"
# วนลูปส่งข้อมูลทุก 5 วินาที
print("Publishing sensor data...")
while True:
try:
# อ่านค่า Sensor
temp, hum = read_sensor()
if temp is not None and hum is not None:
# สร้างข้อมูล JSON
data = {
"temperature": temp,
"humidity": hum,
"timestamp": time.ticks_ms(),
"unit": "celsius"
}
# แปลงเป็น JSON String
payload = json.dumps(data)
# ส่งข้อมูลไปยัง Broker
client.publish(topic_temp, payload)
print(f"Published: {payload}")
# แยกส่งค่าความชื้น
client.publish(topic_humidity, str(hum))
else:
print("Failed to read sensor")
# รอ 5 วินาที
time.sleep(5)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
การทดสอบ Publish:
คุณสามารถทดสอบการรับข้อความด้วย:
- ใช้ MQTT.fx (Desktop Client)
- ใช้ HiveMQ Web Client (Browser)
- ใช้ Command Line:
mosquitto_sub -h broker.hivemq.com -t "sensor/#"
🎯 ตัวอย่างโปรเจกต์จริง: Smart Plant Monitoring
🌱 โปรเจกต์: ระบบเฝ้าระวังพืชอัจฉริยะ
สร้างระบบที่:
- ✅ วัดความชื้นในดิน (Soil Moisture Sensor)
- ✅ วัดอุณหภูมิและความชื้นอากาศ (DHT22)
- ✅ ส่งข้อมูลไปยัง Cloud Platform
- ✅ แจ้งเตือนเมื่อดินแห้ง
Hardware ที่ต้องใช้:
- 1. ESP32 DevKit - ฿150
- 2. Soil Moisture Sensor - ฿50
- 3. DHT22 Sensor - ฿80
- 4. Jumper Wires - ฿30
- 5. Breadboard - ฿40
วงจรการต่อ:
ESP32 Sensors
─────────────────────────────────
GPIO 4 → DHT22 Data Pin
GPIO 34 → Soil Moisture Sensor A0
GND → Sensors GND
3.3V → Sensors VCC
โค้ดทั้งหมด:
# ESP32 Smart Plant Monitoring System
# ระบบเฝ้าระวังพืชอัจฉริยะด้วย MQTT
import network
import time
import json
from umqtt.simple import MQTTClient
from machine import Pin, ADC
import dht
# ============ Configuration ============
WIFI_SSID = "your_wifi_ssid"
WIFI_PASSWORD = "your_wifi_password"
MQTT_BROKER = "broker.hivemq.com"
MQTT_PORT = 1883
MQTT_CLIENT_ID = "plant_monitor_" + str(time.ticks_ms())
# Topic สำหรับส่งข้อมูล
TOPIC_SENSOR = b"plant/sensor"
TOPIC_ALERT = b"plant/alert"
# ============ Sensor Setup ============
dht_sensor = dht.DHT22(Pin(4))
soil_sensor = ADC(Pin(34))
soil_sensor.atten(ADC.ATTN_11DB) # อ่านค่า 0-3.3V
# ============ WiFi Connection ============
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to WiFi...')
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
timeout = 10
while not wlan.isconnected() and timeout > 0:
print('.', end='')
time.sleep(1)
timeout -= 1
return wlan.isconnected()
# ============ Read Sensors ============
def read_sensors():
"""อ่านค่าจากทุก Sensor"""
try:
# อ่าน DHT22
dht_sensor.measure()
temp = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# อ่าน Soil Moisture (ค่ายิ่งน้อย ดินยิ่งแห้ง)
soil_raw = soil_sensor.read()
soil_moisture = (4095 - soil_raw) / 4095 * 100 # แปลงเป็น %
return temp, humidity, soil_moisture
except Exception as e:
print(f"Sensor error: {e}")
return None, None, None
# ============ Check Alert ============
def check_alert(soil_moisture):
"""ตรวจสอบว่าควรแจ้งเตือนหรือไม่"""
if soil_moisture < 30: # ความชื้นต่ำกว่า 30%
return True, f"⚠️ Soil is dry! Moisture: {soil_moisture:.1f}%"
return False, None
# ============ Main Program ============
if __name__ == "__main__":
print("🌱 Smart Plant Monitoring System")
print("=" * 40)
if connect_wifi():
print("✅ WiFi connected")
# เชื่อมต่อ MQTT
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, MQTT_PORT)
client.connect()
print("✅ MQTT connected")
# ตัวแปรสำหรับนับ
counter = 0
# วนลูปส่งข้อมูลทุก 30 วินาที
while True:
try:
counter += 1
print(f"\n--- Reading #{counter} ---")
# อ่านค่า Sensor
temp, humidity, soil = read_sensors()
if temp is not None:
# สร้างข้อมูล JSON
data = {
"temperature": round(temp, 1),
"humidity": round(humidity, 1),
"soil_moisture": round(soil, 1),
"timestamp": time.ticks_ms(),
"status": "healthy" if soil > 30 else "needs_water"
}
payload = json.dumps(data)
# ส่งข้อมูล Sensor
client.publish(TOPIC_SENSOR, payload)
print(f"📤 Published: {payload}")
# ตรวจสอบ Alert
is_alert, alert_msg = check_alert(soil)
if is_alert:
client.publish(TOPIC_ALERT, alert_msg)
print(f"🚨 ALERT: {alert_msg}")
print(f"✅ Temperature: {temp}°C")
print(f"✅ Humidity: {humidity}%")
print(f"✅ Soil Moisture: {soil:.1f}%")
else:
print("❌ Failed to read sensors")
# รอ 30 วินาที
print("⏳ Waiting 30 seconds...")
time.sleep(30)
except Exception as e:
print(f"❌ Error: {e}")
time.sleep(5)
else:
print("❌ Failed to connect WiFi")
🔧 การแก้ปัญหาที่พบบ่อย
❌ ปัญหา: เชื่อมต่อ WiFi ไม่ได้
สาเหตุ: ชื่อ WiFi หรือ Password ผิด
วิธีแก้: ตรวจสอบ WIFI_SSID และ WIFI_PASSWORD ให้ถูกต้อง
❌ ปัญหา: เชื่อมต่อ MQTT Broker ไม่ได้
สาเหตุ: ไม่มี Internet หรือ Broker ล่ม
วิธีแก้: ลองใช้ Broker อื่น (เช่น test.mosquitto.org) หรือตรวจสอบ Internet
❌ ปัญหา: DHT22 อ่านค่าไม่ได้
สาเหตุ: เวลาอ่านไม่ถี่พอ (ต้องห่าง 2 วินาที)
วิธีแก้: เพิ่ม time.sleep(2) ระหว่างการอ่าน
❌ ปัญหา: ESP32 รีเซ็ตเอง
สาเหตุ: ไฟไม่เพียงพอหรือมี Bug ในโค้ด
วิธีแก้: ใช้ Power Supply ที่เหมาะสม (2A+) หรือเพิ่ม try-except
📚 สรุป
ในบทความนี้ คุณได้เรียนรู้:
- วิธีการติดตั้ง MicroPython บน ESP32
- แนวคิดพื้นฐานของ MQTT Protocol
- การเขียนโปรแกรม Publish/Subscribe ด้วย MicroPython
- การสร้างโปรเจกต์ IoT จริง (Smart Plant Monitoring)
- การแก้ปัญหาที่พบบ่อย
🎯 ถัดไป
หวังว่าบทความนี้จะเป็นประโยชน์! ถ้ามีคำถาม สอบถามได้ที่ Community ของเรา
🌱 Happy Making! 🚀