#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
const char* ssid = "Wokwi-GUEST"; // SSID ของ Wi-Fi
const char* password = ""; // รหัสผ่านของ Wi-Fi
const char* scriptURL = "https://script.google.com/macros/s/AKfycbxhu2yN9WfhCRVRpfILCORqQUSEJqVd3wb3aoALktnqJvcQBYJJmpaifXOF2vIWpmUU/exec"; // URL ของ Google Apps Script
const int analogPin = 34; // Pin สำหรับ MQ-135
const int dhtPin = 15; // Pin สำหรับ DHT11
LiquidCrystal_I2C lcd(0x27, 20, 4); // Address 0x27 สำหรับจอ LCD 20x4
DHT dht(dhtPin, DHT11); // สร้าง object สำหรับ DHT11
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
lcd.setCursor(0, 0);
lcd.print("MQ-135 GAS SENSOR");
}
void loop() {
// อ่านค่า DHT11
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// อ่านค่า MQ-135
int sensorValue = analogRead(analogPin);
float voltage = sensorValue * (3.3 / 4095.0);
int alarm = (sensorValue > 2000) ? 1 : 0; // เปลี่ยน '2000' เป็นค่า threshold ที่ต้องการ
// แสดงผลบนจอ LCD
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
lcd.setCursor(0, 2);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print(" %");
lcd.setCursor(0, 3);
lcd.print("GAS ADC: ");
lcd.print(sensorValue);
lcd.print(" V:");
lcd.print(voltage);
// ส่งข้อมูลไปยัง Google Sheets
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(scriptURL);
http.addHeader("Content-Type", "application/json");
String postData = "{\"value\":" + String(sensorValue) + ",\"voltage\":" + String(voltage) + ",\"alarm\":" + String(alarm) + ",\"temperature\":" + String(temperature) + ",\"humidity\":" + String(humidity) + "}";
int httpResponseCode = http.POST(postData);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Success");
Serial.println(httpResponseCode);
Serial.println(response);
lcd.setCursor(0, 4);
lcd.print("Status: Success ");
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
lcd.setCursor(0, 4);
lcd.print("Status: Failed ");
}
http.end();
} else {
Serial.println("WiFi Disconnected");
lcd.setCursor(0, 4);
lcd.print("Status: No WiFi ");
}
delay(20000); // ส่งข้อมูลทุกๆ 20 วินาที
}