#include <DHT.h>
#include <WiFi.h>
#
#define DHTPIN 2 // Pin where the DHT sensor is connected
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define Relay 3 // Pin for the relay
#define Buzzer 4 // Pin for the buzzer
DHT dht(DHTPIN, DHTTYPE);
// Wi-Fi credentials
const char* ssid = "your_SSID"; // Ganti dengan nama SSID Wi-Fi Anda
const char* password = "your_PASSWORD"; // Ganti dengan password Wi-Fi Anda
void setup() {
Serial.begin(115200);
Serial.println(F("DHT-On test"));
dht.begin();
pinMode(Relay, OUTPUT); // Set relay pin as output
pinMode(Buzzer, OUTPUT); // Set buzzer pin as output
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
delay(2000); // Wait for sensor to stabilize
// Read humidity and temperature
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
float fahrenheit = dht.readTemperature(true);
// Check if readings failed
if (isnan(humidity) || isnan(temperature) || isnan(fahrenheit)) {
Serial.println(F("Failed to read from DHT sensor"));
return;
}
// Print humidity and temperature to Serial Monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% Temperature: ");
Serial.print(temperature);
Serial.print("°C ");
Serial.print(fahrenheit);
Serial.println("°F");
// Send data to PHP script
sendDataToPHP(humidity, temperature, fahrenheit);
// Control relay and buzzer based on temperature
if (temperature > 30.0) {
digitalWrite(Relay, HIGH); // Turn on relay
digitalWrite(Buzzer, HIGH); // Turn on buzzer
} else if (temperature < 25.0) {
digitalWrite(Relay, LOW); // Turn off relay
digitalWrite(Buzzer, LOW); // Turn off buzzer
}
delay(1000); // Delay before next loop
}
// Function to send data to PHP script
void sendDataToPHP(float humidity, float temperature, float fahrenheit) {
HTTPClient http;
String url = "http://localhost/dht/save_data.php"; // Ganti dengan path PHP Anda
http.begin(url); // Specify the URL
// Specify content type and HTTP method
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Create POST data
String postData = "humidity=" + String(humidity) + "&temperature_celsius=" + String(temperature) + "&temperature_fahrenheit=" + String(fahrenheit);
// Send HTTP POST request
int httpResponseCode = http.POST(postData);
if (httpResponseCode > 0) {
Serial.println("Data sent successfully");
} else {
Serial.println("Error in sending data");
}
http.end(); // Close connection
}