#include <DHT.h>
#include <WiFi.h>
#include "DHTesp.h"
#include "ThingSpeak.h"
const int DHT_PIN = 15; // DHT22 sensor GPIO Pin
const char* WIFI_NAME = "Wokwi-GUEST"; // WiFi SSID
const char* WIFI_PASSWORD = ""; // WiFi Password
const int myChannelNumber = 2589125; // ThingSpeak channel number (semicolon added)
const char* myApiKey = "U0KBDX2IRZK0Z9J6"; // ThingSpeak API key
const char* server = "api.thingspeak.com"; // ThingSpeak server address
DHTesp dhtSensor; // Create an instance of the DHTesp library
WiFiClient client; // Create a WiFi client object
#define MoisensorPin 33
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22); // Initialize the DHT22 sensor
WiFi.begin(WIFI_NAME, WIFI_PASSWORD); // Connect to the WiFi network
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("WiFi not connected");
}
Serial.println("WiFi connected!");
Serial.println("Local IP: " + String(WiFi.localIP())); // Print the local IP address
WiFi.mode(WIFI_STA); // Set the WiFi mode to station mode
ThingSpeak.begin(client); // Initialize the ThingSpeak library
}
void loop() {
// Read temperature and humidity from DHT sensor
float humidity = dhtSensor.getHumidity();
float temperatureC = dhtSensor.getTemperature();
float temperatureF = dhtSensor.toFahrenheit(temperatureC); // Fahrenheit
// Read soil moisture sensor value
int moistureValue = analogRead(MoisensorPin);
moistureValue = map(moistureValue, 0, 4095, 0, 100); // Map ADC range to percentage
moistureValue = 100 - moistureValue; // Invert percentage
// Print sensor values
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.print(" °C, ");
Serial.print(temperatureF);
Serial.print(" °F | Humidity: ");
Serial.print(humidity);
Serial.print(" % | Soil Moisture: ");
Serial.print(moistureValue);
Serial.println(" %");
// Set the fields with the values
ThingSpeak.setField(1, temperatureC);
ThingSpeak.setField(2, humidity);
ThingSpeak.setField(3, moistureValue);
// Write to ThingSpeak
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
if(x == 200) {
Serial.println("Channel update successful.");
} else {
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
delay(200); // ThingSpeak only allows updates every 15 seconds
}