#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"
// กำหนดพินสำหรับ DHT22
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// กำหนดค่าจอ OLED
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// กำหนดพินสำหรับ RGB LED
int redPin = 11;
int greenPin = 10;
int bluePin = 9;
// กำหนดพินสำหรับ Gas Sensor และ Buzzer
const int gasPin = A0;
const int buzzerPin = 8;
// กำหนดระดับค่าความเข้มข้นแก๊สที่เริ่มแจ้งเตือน (ปรับเปลี่ยนได้ตามต้องการ 0 - 1023)
const int gasThreshold = 300;
void setup() {
dht.begin();
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(gasPin, INPUT);
pinMode(buzzerPin, OUTPUT);
// เริ่มต้นการทำงานจอ OLED
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
for(;;); // ถ้าหาจอไม่เจอจะหยุดการทำงาน
}
display.setTextColor(WHITE);
}
// ฟังก์ชันสำหรับตั้งสี RGB LED (Common Cathode)
void setRGB(int r, int g, int b,) {
analogWrite(redPin, r);
analogWrite(greenPin, g);
analogWrite(bluePin, b);
}
void loop() {
delay(1000); // หน่วงเวลาอ่านค่าเซนเซอร์
float t = dht.readTemperature();
float h = dht.readHumidity();
int gasValue = analogRead(gasPin); // อ่านค่าระดับแก๊ส
// ตรวจสอบว่าอ่านค่า DHT สำเร็จหรือไม่
if (isnan(t) || isnan(h)) {
return;
}
// ระบบตรวจสอบแก๊สและสั่งงาน Buzzer
bool gasAlert = false;
if (gasValue > gasThreshold) {
gasAlert = true;
tone(buzzerPin, 1000); // ส่งเสียงเตือนความถี่ 1000 Hz
} else {
noTone(buzzerPin); // ปิดเสียงเมื่อระดับแก๊สปกติ
}
String statusText = "";
// เงื่อนไขเปลี่ยนสีหลอดไฟ RGB
if (gasAlert) {
setRGB(255, 0, 0); // แก๊สรั่ว: ไฟแดงเตือน
statusText = "GAS ALERT!";
} else {
if (t <= 25.0) {
setRGB(0, 255, 0); // สีเขียว
statusText = "Cool";
} else if (t > 25.0 && t <= 40.0) {
setRGB(255, 255, 0); // สีเหลือง
statusText = "Warm";
} else {
setRGB(255, 0, 0); // สีแดง
statusText = "Hot";
}
}
// อัปเดตข้อมูลขึ้นจอ OLED
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.println("--- MONITOR SYSTEM ---");
display.setCursor(0, 16);
display.print("Temp : ");
display.print(t, 1);
display.println(" C");
display.setCursor(0, 28);
display.print("Hum : ");
display.print(h, 1);
display.println(" %");
display.setCursor(0, 40);
display.print("Gas : ");
display.print(gasValue);
if (gasAlert) display.print(" [!]");
display.println();
display.setCursor(0, 52);
display.print("Status: ");
display.println(statusText);
display.display();
}