#if defined(ESP8266)
#include <ESP8266WiFi.h> // Include WiFi library for ESP8266 if used
#elif defined(ESP32)
#include <WiFi.h> // Include WiFi library for ESP32 if used
#endif
// #include <ESP8266WiFi.h> // Redundant, commented out
#include "DHTesp.h" // Include library for DHT sensor (temperature and humidity)
#include "ThingSpeak.h" // Include ThingSpeak library for IoT data communication
#include <HTTPClient.h> // Include HTTPClient library for sending HTTP requests
#include <UrlEncode.h> // Include library for URL encoding
// Pin configuration
const int DHT_PIN = 15; // Pin for DHT22 sensor
const int LED_PIN = 13; // Pin for LED status indicator
const int sensor_pin = 34; // Analog pin for soil moisture sensor
// WiFi credentials
const char* WIFI_NAME = "Wokwi-GUEST"; // WiFi SSID
const char* WIFI_PASSWORD = ""; // WiFi password
// ThingSpeak configurations
const int myChannelNumber = 2798284; // ThingSpeak channel number
const char* myApiKey = "QQDYSJH1D5D5JQ02"; // ThingSpeak API key
// const char* server = "api.thingspeak.com"; // Unused, commented out
const char* mqtt_server = "mqtt3.thingspeak.com"; // MQTT server address
const int mqtt_port = 1883; // MQTT server port
const char* mqtt_client_id = "PDQdBhEdJjwQLDMGKywMLzg"; // MQTT client ID
const char* mqtt_username = "PDQdBhEdJjwQLDMGKywMLzg"; // MQTT username
const char* mqtt_password = "rrhXucjyKujGsIegA1I3vO0R"; // MQTT password
// Initialize DHT sensor and WiFi client
DHTesp dhtSensor; // DHT sensor object
WiFiClient client; // WiFi client object
// Function to send a WhatsApp message
void sendMessage(String message) {
String url = "https://gate.whapi.cloud/messages/text"; // Base URL for WhatsApp API
// Create JSON payload
String payload = "{";
payload += "\"to\":\"[email protected]\","; // Target WhatsApp user
payload += "\"quoted\":\"T85L1gN0p0-.1dZ6gD9p\","; // Quoted message reference
payload += "\"ephemeral\":604800,"; // Ephemeral message expiry
payload += "\"edit\":\"PFGRd_LCYP2kRtFhF2-wcoWD\","; // Edit token
payload += "\"body\":\"" + message + "\","; // Message body
payload += "\"typing_time\":0,"; // Typing duration (ms)
payload += "\"no_link_preview\":true,"; // Disable link preview
payload += "\"mentions\":[\"5744114926\"],"; // Mentioned users
payload += "\"view_once\":true"; // Mark message as view-once
payload += "}";
HTTPClient http; // Initialize HTTP client
http.begin(url); // Connect to API endpoint
// Add headers for HTTP request
http.addHeader("Content-Type", "application/json"); // Specify JSON content type
http.addHeader("Authorization", "Bearer mi18vRAzKUE9E0j1wkEjoXEztEpQkLrK"); // Bearer token for API
http.addHeader("accept", "application/json"); // Accept JSON response
// Send HTTP POST request
int httpResponseCode = http.POST(payload);
// Handle response
if (httpResponseCode == 200) {
Serial.println("Message sent successfully"); // Success
} else {
Serial.println("Error sending the message"); // Error
Serial.print("HTTP response code: ");
Serial.println(httpResponseCode);
}
http.end(); // Free resources
}
// Setup function (runs once at start)
void setup() {
Serial.begin(115200); // Initialize serial communication
dhtSensor.setup(DHT_PIN, DHTesp::DHT22); // Configure DHT sensor
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
WiFi.begin(WIFI_NAME, WIFI_PASSWORD); // Connect to WiFi network
// Wait for WiFi connection
while (WiFi.status() != WL_CONNECTED) {
delay(1000); // Retry every second
Serial.println("Wifi not connected"); // Print connection status
}
Serial.println("Wifi connected !"); // Connection successful
Serial.println("Local IP: " + String(WiFi.localIP())); // Print IP address
WiFi.mode(WIFI_STA); // Set WiFi to station mode
ThingSpeak.begin(client); // Initialize ThingSpeak connection
}
// Main loop (runs repeatedly)
void loop() {
TempAndHumidity data = dhtSensor.getTempAndHumidity(); // Read temperature and humidity
int val = analogRead(sensor_pin); // Read soil moisture value
// Send data to ThingSpeak
ThingSpeak.setField(1, data.temperature); // Field 1: Temperature
ThingSpeak.setField(2, data.humidity); // Field 2: Humidity
ThingSpeak.setField(3, val); // Field 3: Soil moisture
// Check sensor values and send message if conditions are met
if (data.temperature > 35 || data.temperature < 12 || data.humidity > 70 || data.humidity < 40) {
sendMessage("Soil moisture is 22%. It's recommended that irrigation is to be done today to prevent yield loss.");
} else {
sendMessage("Soil moisture level is 20" + String(data.humidity) + "%. " + "Irrigation is required today.");
}
// Write data to ThingSpeak and check for success
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
// Print sensor readings to serial monitor
Serial.println("Temp: " + String(data.temperature, 2) + "°C"); // Temperature
Serial.println("Humidity: " + String(data.humidity, 1) + "%"); // Humidity
Serial.println("Soil Moisture: " + String(val)); // Soil moisture
if (x == 200) {
Serial.println("Data pushed successfully\n"); // Success
} else {
Serial.println("Push error" + String(x)); // Error
}
Serial.println("---");
delay(3000); // Wait for 3 seconds before next loop
}