📑 เนื้อหาในบทความ
🎯 ภาพรวมโปรเจกต์
ในบทความนี้คุณจะได้เรียนรู้วิธีสร้างระบบติดตามสภาพแวดล้อมอัจฉริะ (Smart Monitoring System) ที่สามารถ:
- วัดอุณหภูมิและความชื้นในห้อง
- ตรวจจับการเคลื่อนไหวของคนหรือสัตว์เลี้ยง
- ส่งข้อมูลไปยัง CynoIoT Platform แบบเรียลไทม์
- แจ้งเตือนเมื่อค่าเกินกำหนด
- ประหยัดพลังงานด้วย Deep Sleep Mode
💡 เกร็ดความรู้: ระบบนี้เหมาะสำหรับการติดตามสภาพแวดล้อมในโกดังสินค้า, ห้องเก็บของ, ห้องน้ำ, หรือแม้แต่ในบ้านเพื่อตรวจสอบความชื้นและอุณหภูมิ
🔧 อุปกรณ์ที่ต้องใช้
Hardware Components
ไมโครคอนโทรลเลอร์
- • ESP32 DevKit V1 (฿150-250)
- • หรือ ESP32-WROOM-32
เซ็นเซอร์
- • DHT22 (อุณหภูมิ/ความชื้น) - ฿60-90
- • PIR Motion Sensor (HC-SR501) - ฿40-60
อุปกรณ์เสริม
- • Breadboard และ Jumper wires
- • USB Cable สำหรับ ESP32
- • Resistor 10kΩ (ถ้าจำเป็น)
Software
- • Arduino IDE หรือ PlatformIO
- • CynoIoT Account (สมัครฟรี)
- • WiFi เชื่อมต่ออินเทอร์เน็ต
💰 งบประมาณรวม: ประมาณ ฿300-500 ขึ้นอยู่กับว่าคุณมีอุปกรณ์อะไรอยู่แล้วบ้าง
⚡ การต่อวงจร
Pin Connections
| ESP32 Pin | Sensor Pin | หมายเหตุ |
|---|---|---|
| 3.3V | VCC (DHT22, PIR) | จ่ายไฟ 3.3V |
| GND | GND (DHT22, PIR) | กราวด์ |
| GPIO 4 | DATA (DHT22) | สัญญาณ DHT22 |
| GPIO 27 | OUT (PIR) | สัญญาณ PIR |
⚠️ คำเตือน: ตรวจสอบให้แน่ใจว่า DHT22 ใช้ 3.3V ไม่ใช่ 5V เพราะ ESP32 ใช้ 3.3V logic หากใช้ 5V อาจทำให้เสียหายได้
💻 การเขียนโปรแกรม
ติดตั้ง Libraries
ก่อนเริ่มเขียนโค้ด ให้ติดตั้ง libraries ที่จำเป็นใน Arduino IDE:
# Libraries ที่ต้องติดตั้ง
1. DHT sensor library by Adafruit
2. Adafruit Unified Sensor
3. PubSubClient (สำหรับ MQTT)
4. ArduinoJson (สำหรับจัดการ JSON)โค้ดหลัก (Main Code)
นี่คือโค้ดที่สมบูรณ์สำหรับระบบ Smart Monitoring:
#include <WiFi.h>
#include <DHT.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
// ========== ตั้งค่า WiFi ==========
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
// ========== ตั้งค่า CynoIoT ==========
const char* cynoiot_server = "api.cynoiot.com";
const int cynoiot_port = 1883;
const char* device_id = "YOUR_DEVICE_ID";
const char* api_key = "YOUR_API_KEY";
// ========== ตั้งค่า Sensors ==========
#define DHTPIN 4
#define DHTTYPE DHT22
#define PIR_PIN 27
// ตั้งค่า threshold สำหรับการแจ้งเตือน
const float TEMP_HIGH_THRESHOLD = 35.0; // อุณหภูมิสูงเกินไป (°C)
const float TEMP_LOW_THRESHOLD = 18.0; // อุณหภูมิต่ำเกินไป (°C)
const float HUMIDITY_HIGH_THRESHOLD = 70.0; // ความชื้นสูงเกินไป (%)
// ตั้งค่า Deep Sleep (วินาที)
#define SLEEP_INTERVAL 60 // ส่งข้อมูลทุก 1 นาที
DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient client(espClient);
HTTPClient http;
// Variables สำหรับเก็บค่า
float temperature = 0.0;
float humidity = 0.0;
bool motionDetected = false;
unsigned long lastMotionTime = 0;
// ฟังก์ชันเชื่อมต่อ WiFi
void connectToWiFi() {
Serial.println("\n📡 Connecting to WiFi...");
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\n✅ WiFi connected!");
Serial.println("IP address: " + WiFi.localIP().toString());
} else {
Serial.println("\n❌ WiFi connection failed!");
}
}
// ฟังก์ชันเชื่อมต่อ CynoIoT MQTT
void connectToCynoIoT() {
while (!client.connected()) {
Serial.print("🔗 Connecting to CynoIoT...");
if (client.connect("ESP32Client", device_id, api_key)) {
Serial.println(" ✅");
client.subscribe("cynoiot/" + String(device_id) + "/commands");
} else {
Serial.print(" failed, rc=");
Serial.print(client.state());
Serial.println(" retrying in 5 seconds");
delay(5000);
}
}
}
// ฟังก์ชันอ่านค่าจากเซ็นเซอร์
void readSensors() {
Serial.println("\n📖 Reading sensors...");
// อ่าน DHT22
temperature = dht.readTemperature();
humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("❌ Failed to read from DHT sensor!");
return;
}
Serial.printf("🌡️ Temperature: %.2f°C\n", temperature);
Serial.printf("💧 Humidity: %.2f%%\n", humidity);
// อ่าน PIR Motion Sensor
motionDetected = digitalRead(PIR_PIN);
if (motionDetected) {
lastMotionTime = millis();
Serial.println("🚶 Motion detected!");
}
}
// ฟังก์ชันสร้าง JSON payload
String createSensorPayload() {
StaticJsonDocument<256> doc;
doc["device_id"] = device_id;
doc["timestamp"] = millis();
doc["temperature"] = temperature;
doc["humidity"] = humidity;
doc["motion"] = motionDetected;
String payload;
serializeJson(doc, payload);
return payload;
}
// ฟังก์ชันส่งข้อมูลไปยัง CynoIoT
void sendToCynoIoT() {
String payload = createSensorPayload();
String topic = "cynoiot/" + String(device_id) + "/sensors";
Serial.println("📤 Sending data to CynoIoT...");
Serial.println("Payload: " + payload);
if (client.publish(topic.c_str(), payload.c_str())) {
Serial.println("✅ Data sent successfully!");
} else {
Serial.println("❌ Failed to send data");
}
}
// ฟังก์ชันตรวจสอบและแจ้งเตือน
void checkThresholds() {
String alertMsg = "";
if (temperature > TEMP_HIGH_THRESHOLD) {
alertMsg = "⚠️ อุณหภูมิสูงเกินกำหนด! " + String(temperature) + "°C";
} else if (temperature < TEMP_LOW_THRESHOLD) {
alertMsg = "❄️ อุณหภูมิต่ำเกินกำหนด! " + String(temperature) + "°C";
}
if (humidity > HUMIDITY_HIGH_THRESHOLD) {
alertMsg += " | 💧 ความชื้นสูงเกินกำหนด! " + String(humidity) + "%";
}
if (alertMsg != "") {
Serial.println("🚨 " + alertMsg);
// ส่งแจ้งเตือนไปยัง CynoIoT
String alertTopic = "cynoiot/" + String(device_id) + "/alerts";
client.publish(alertTopic.c_str(), alertMsg.c_str());
}
}
// MQTT callback function
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("📩 Message arrived [");
Serial.print(topic);
Serial.print("]: ");
for (unsigned int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("\n====================================");
Serial.println("🚀 CynoIoT Smart Monitoring System");
Serial.println("====================================\n");
// ตั้งค่า pin modes
pinMode(PIR_PIN, INPUT);
dht.begin();
// เชื่อมต่อ WiFi
connectToWiFi();
// ตั้งค่า MQTT
client.setServer(cynoiot_server, cynoiot_port);
client.setCallback(callback);
// เชื่อมต่อ CynoIoT
connectToCynoIoT();
Serial.println("✅ Setup complete! Starting monitoring...\n");
}
void loop() {
// ตรวจสอบการเชื่อมต่อ MQTT
if (!client.connected()) {
connectToCynoIoT();
}
client.loop();
// อ่านค่าเซ็นเซอร์
readSensors();
// ส่งข้อมูลไปยัง CynoIoT
sendToCynoIoT();
// ตรวจสอบ threshold และแจ้งเตือน
checkThresholds();
Serial.println("\n⏰ Going to deep sleep for " + String(SLEEP_INTERVAL) + " seconds...\n");
// เข้าสู่โหมด Deep Sleep
ESP32.deepSleep(SLEEP_INTERVAL * 1000000);
}💡 เคล็ดลับ: อย่าลืมเปลี่ยนค่า WiFi credentials, device_id, และ api_key ให้ตรงกับบัญชี CynoIoT ของคุณ
🌐 เชื่อมต่อ CynoIoT Platform
ขั้นตอนการเชื่อมต่อ
สมัครบัญชี CynoIoT
ไปที่ cynoiot.com และสมัครบัญชีฟรี
สร้าง Device ใหม่
ใน Dashboard ให้สร้าง device ประเภท ESP32 เพื่อรับ device_id และ api_key
ตั้งค่า Dashboard
สร้าง dashboard เพื่อแสดงกราฟอุณหภูมิ ความชื้น และการตรวจจับการเคลื่อนไหว
ตั้งค่า Alerts
กำหนดเงื่อนไขการแจ้งเตือนผ่าน LINE, Telegram หรือ Email
📚 เอกสารเพิ่มเติม: ติดตามเอกสารประกอบเร็วๆ นี้
✅ การทดสอบ
การตรวจสอบการทำงาน
1. ตรวจสอบ Serial Monitor
เปิด Serial Monitor (115200 baud) และดูว่าข้อมูลแสดงถูกต้อง:
- ✅ เชื่อมต่อ WiFi สำเร็จ
- ✅ เชื่อมต่อ CynoIoT สำเร็จ
- ✅ อ่านค่า DHT22 ได้
- ✅ ตรวจจับ motion ได้
2. ทดสอบเซ็นเซอร์
ลองปอดลมบน DHT22 เพื่อเปลี่ยนค่าอุณหภูมิ และเอามือไปโบกหน้า PIR sensor เพื่อทดสอบ
3. ตรวจสอบ CynoIoT Dashboard
ไปที่ Dashboard ของคุณและดูว่าข้อมูลมาถึงแบบเรียลไทม์หรือไม่
🔋 ประหยัดพลังงานด้วย Deep Sleep
โค้ดนี้ใช้ Deep Sleep Mode เพื่อประหยัดแบตเตอรี่ ESP32 จะเข้านอนทุก ๆ 1 นาที (ตั้งค่าใน SLEEP_INTERVAL) ซึ่งช่วยลดการใช้พลังงานลงได้มาก
การปรับจูนระยะเวลา Sleep
- 30 วินาที: ติดตามแบบเรียลไทม์ แต่ใช้พลังงานมาก
- 1-2 นาที: สมดุลระหว่างความเร็วและประหยัดพลังงาน (แนะนำ)
- 5-10 นาที: ประหยัดมาก แต่อาจไม่เหมาะกับการติดตามแบบเรียลไทม์
⚠️ หมายเหตุ: หากต้องการใช้งาน ESP32 กับแบตเตอรี่แบบถาวร ให้พิจารณาใช้ตัวต้านทานตัวดึงของ USB และปิดใช้งาน peripherals ที่ไม่จำเป็น
🔧 แก้ปัญหาที่พบบ่อย
❌ ปัญหา: ESP32 เชื่อมต่อ WiFi ไม่ได้
สาเหตุ: รหัสผ่านผิด, อยู่ไกลเกินไป, หรือ WiFi รุนแรงเกินไป
วิธีแก้: ตรวจสอบ SSID และ password ลองย้าย ESP32 ให้ใกล้ router มากขึ้น
❌ ปัญหา: DHT22 อ่านค่าไม่ได้
สาเหตุ: ต่อสายผิด, VCC ไม่เสถียร, หรือตัวต้านทานไม่พอ
วิธีแก้: ตรวจสอบการต่อสาย, เพิ่มตัวต้านทาน 10kΩ ระหว่าง VCC และ DATA
❌ ปัญหา: MQTT เชื่อมต่อไม่ได้
สาเหตุ: device_id หรือ api_key ผิด, server ล่ม
วิธีแก้: ตรวจสอบค่าที่ได้จาก CynoIoT Dashboard, ลอง ping api.cynoiot.com
❌ ปัญหา: PIR Sensor ไม่ตรวจจับ
สาเหตุ: ปรับความไวไม่ถูกต้อง, อุณหภูมิแวดล้อม
วิธีแก้: ปรับ potentiometer บน PIR sensor, รอให้ sensor warm up 1-2 นาที
🎉 สรุป
ยินดีด้วย! คุณได้สร้างระบบ Smart Monitoring ด้วย ESP32 และ CynoIoT เรียบร้อยแล้ว ระบบนี้สามารถ:
- ติดตามอุณหภูมิและความชื้นแบบเรียลไทม์
- ตรวจจับการเคลื่อนไหว
- แจ้งเตือนเมื่อค่าผิดปกติ
- ประหยัดพลังงานด้วย Deep Sleep
จากที่นี่คุณสามารถพัฒนาต่อยอดได้ เช่น เพิ่มเซ็นเซอร์วัดควัน, แสง, หรือเสียง และสร้าง automation rules ที่ซับซ้อนขึ้นบน CynoIoT Platform