#include <LiquidCrystal_I2C.h>
#include <NewPing.h>
#include <DHT.h>
#include <WiFi.h>
#include <HTTPClient.h>
#define DHTPIN 14
#define DHTTYPE DHT22
#define TRIGGER_PIN 18
#define ECHO_PIN 17
#define MAX_DISTANCE 200
#define PHOTO_PIN 34
#define BUZZER_PIN 12
#define RED_LED_PIN 19
#define BLUE_LED_PIN 26
const float GAMMA = 0.7;
const float RL10 = 50;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* server = "http://api.thingspeak.com/update";
const char* apiKey = "K4QM3JCOB8FOWVV4";
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(115200);
dht.begin();
lcd.init();
lcd.backlight();
pinMode(BUZZER_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
pinMode(BLUE_LED_PIN, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
float distance = sonar.ping_cm();
int analogValue = analogRead(PHOTO_PIN);
float voltage = analogValue / 4095.0 * 3.3 ;
float resistance = 2000 * voltage / (1 - voltage / 3.3);
float lightIntensityLux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA))/1.808;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print("C");
delay(500);
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print("%");
delay(500);
lcd.setCursor(0, 0);
lcd.print("Light: ");
lcd.print(lightIntensityLux);
lcd.print(" lux");
delay(500);
lcd.setCursor(0, 1);
lcd.print("Water: ");
lcd.print(distance);
lcd.print(" cm");
delay(1000);
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("Light Intensity: ");
Serial.print(lightIntensityLux);
Serial.println(" lux");
Serial.print("Water Level: ");
Serial.print(distance);
Serial.println(" cm");
if (temperature > 35 && humidity > 60 && distance < 20 && lightIntensityLux > 200) {
digitalWrite(RED_LED_PIN, HIGH);
digitalWrite(BLUE_LED_PIN, LOW);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Danger!");
tone(BUZZER_PIN, 1000, 1000);
} else {
digitalWrite(RED_LED_PIN, LOW);
digitalWrite(BLUE_LED_PIN, HIGH);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Safe");
}
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(server) + "?api_key=" + apiKey +
"&field1=" + String(temperature) +
"&field2=" + String(humidity) +
"&field3=" + String(distance) +
"&field4=" + String(lightIntensityLux);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.print("Data sent to ThingSpeak. Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error in sending data. HTTP response code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi not connected");
}
delay(1000);
}