#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <DHT.h>
#define DHTPIN 4 // DHT22 data pin (GPIO 4)
#define DHTTYPE DHT22 // DHT sensor type
#define SOIL_MOISTURE_PIN 32 // GPIO pin connected to soil moisture sensor
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingSpeak credentials
const char* server = "api.thingspeak.com";
const String apiKey = "ON5UCJE8KSY0HX3K";
const String channelID = "2590735";
WiFiClientSecure client;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
delay(1000);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
dht.begin();
client.setInsecure(); // This disables SSL certificate verification (use only for testing)
Serial.print("Connecting to ThingSpeak...");
if (client.connect(server, 443)) {
Serial.println("Connected to ThingSpeak");
} else {
Serial.println("Connection to ThingSpeak failed...");
}
}
void loop() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
int soilMoisture = analogRead(SOIL_MOISTURE_PIN);
int moisturePercent = map(soilMoisture, 0, 4095, 0, 100); // Assuming ADC range for ESP32
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print("°C Humidity: ");
Serial.print(humidity);
Serial.print("% Soil Moisture: ");
Serial.print(moisturePercent);
Serial.println("%");
// Construct the URL for the GET request
String url = "/update?api_key=" + apiKey +
"&field1=" + String(temperature, 1) +
"&field2=" + String(humidity, 1) +
"&field3=" + String(moisturePercent);
if (!client.connected()) {
Serial.print("Reconnecting to ThingSpeak...");
if (client.connect(server, 443)) {
Serial.println("Reconnected to ThingSpeak");
} else {
Serial.println("Reconnection to ThingSpeak failed...");
delay(5000); // Wait before retrying
return;
}
}
// Make a HTTPS request
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + server + "\r\n" +
"Connection: keep-alive\r\n\r\n");
delay(500);
// Read and print server response
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
// Wait for 15 seconds before sending next data
delay(15000);
}