// library wifi
#include "WiFi.h"
// buat object wifi-client
WiFiClient client;
// library sensor dhtesp
#include "DHTesp.h"
// Pin inisialisasi di modul ESP32
const int DHT_PIN = 15;
const int PH_PIN = 13;
const int SOIL_PIN = 12;
const int WATER_PIN = 4;
const int FERTILIZER_PIN = 5;
// buat object sensor
DHTesp dhtSensor;;
// inisialisasi variable untuk terhubung dengan thingspeak
String thingSpeakAddress = "api.thingspeak.com";
String writeAPIKey;
String tsfield1Name;
String request_string;
// fungsi setup koneksi ke wifi
void setup()
{
// koneksi wifi
Serial.begin(9600);
WiFi.disconnect();
WiFi.begin("Wokwi-GUEST", "");
while ((!(WiFi.status() == WL_CONNECTED))) {
delay(300);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(WATER_PIN,OUTPUT);
pinMode(FERTILIZER_PIN,OUTPUT);
}
void loop()
{
// Baca Data per 500 ms
delay(500);
TempAndHumidity data = dhtSensor.getTempAndHumidity();
float t = data.temperature;
float h = data.humidity;
float p = analogRead(PH_PIN);
float s = analogRead(SOIL_PIN);
kirim_thingspeak(t, h, p, s);
if (isnan(h) || isnan(t) || isnan(p) || isnan(s)) {
Serial.println("Failed to read from All sensor!");
return;
}
// Logic untuk aktivasi Motor Pompa Air dan Pupuk
if (p > 100) {
digitalWrite(WATER_PIN, HIGH);
}
else {
digitalWrite(WATER_PIN, LOW);
}
if (s > 150) {
digitalWrite(FERTILIZER_PIN, HIGH);
}
else {
digitalWrite(FERTILIZER_PIN, LOW);
}
delay(100);
}
// Kirim Data ke Cloud
void kirim_thingspeak(float suhu, float hum, float Ph, float Soil) {
if (client.connect("api.thingspeak.com", 80)) {
request_string = "/update?";
request_string += "key=";
request_string += "AB1280JS2XTMDCOA";
request_string += "&";
request_string += "field1";
request_string += "=";
request_string += suhu;
request_string += "&";
request_string += "field2";
request_string += "=";
request_string += hum;
request_string += "&";
request_string += "field3";
request_string += "=";
request_string += Ph;
request_string += "&";
request_string += "field4";
request_string += "=";
request_string += Soil;
Serial.println(String("GET ") + request_string + " HTTP/1.1\r\n" +
"Host: " + thingSpeakAddress + "\r\n" +
"Connection: close\r\n\r\n");
client.print(String("GET ") + request_string + " HTTP/1.1\r\n" +
"Host: " + thingSpeakAddress + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
}