#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingSpeak API key and URL
const char* apiKey = "NSTBS4GHAGRTC6S6";
const char* server = "api.thingspeak.com";
// Analog pins for nutrient levels (N, P, K) and soil moisture
const int nPin = 34; // Analog pin for Nitrogen (N) level
const int pPin = 35; // Analog pin for Phosphorus (P) level
const int kPin = 32; // Analog pin for Potassium (K) level
const int soilMoisturePin = 33; // Analog pin for soil moisture sensor
// DHT sensor pin
const int dhtPin = 2; // Digital pin for DHT sensor
DHT dht(dhtPin, DHT22);
void setup() {
Serial.begin(115200);
dht.begin();
// 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");
// Initialize analog pins
analogReadResolution(12); // Set ADC resolution to 12 bits
}
void loop() {
// Read sensor values
int nValue = analogRead(nPin);
int pValue = analogRead(pPin);
int kValue = analogRead(kPin);
int soilMoistureValue = analogRead(soilMoisturePin);
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Create the URL for ThingSpeak update
String url = "http://";
url += server;
url += "/update?";
url += "api_key=";
url += apiKey;
url += "&field1=";
url += String(nValue);
url += "&field2=";
url += String(pValue);
url += "&field3=";
url += String(kValue);
url += "&field6=";
url += String(soilMoistureValue);
url += "&field4=";
url += String(temperature);
url += "&field5=";
url += String(humidity);
// Send HTTP GET request to ThingSpeak
HTTPClient http;
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.printf("HTTP Response code: %d\n", httpResponseCode);
Serial.println("Data Uploaded Successfully !!!");
} else {
Serial.println("Error sending HTTP request");
}
http.end();
delay(15000); // Send data every 15 seconds
}