#include <DHT.h>
#include <ThingSpeak.h>
#include <WiFi.h> // Use this for ESP32; for ESP8266, use <ESP8266WiFi.h>
// Replace these with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Replace these with your ThingSpeak channel details
unsigned long channelID = ; // Replace with your ThingSpeak channel ID
const char* writeAPIKey = "MMN70WV92S98NICB"; // Replace with your ThingSpeak API key
// DHT Sensor settings
#define DHTPIN 15 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // Change this to DHT11 if you are using DHT11
DHT dht(DHTPIN, DHTTYPE);
// Ultrasonic sensor settings
#define TRIGGER_PIN 27
#define ECHO_PIN 14
WiFiClient client; // Create a WiFiClient object
void setup() {
Serial.begin(115200);
dht.begin();
// Initialize WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
// Initialize ThingSpeak
ThingSpeak.begin(client);
// Initialize ultrasonic sensor pins
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Read DHT sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Read Ultrasonic sensor
long duration, distance;
// Send a pulse to trigger
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Read the echo pulse duration
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in cm
distance = (duration / 2) / 29.1;
// Print the results to Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\tHumidity: ");
Serial.print(humidity);
Serial.print(" %\tDistance: ");
Serial.print(distance);
Serial.println(" cm");
// Send data to ThingSpeak
ThingSpeak.setField(1, temperature);
ThingSpeak.setField(2, humidity);
ThingSpeak.setField(3, distance);
// Write to ThingSpeak
int x = ThingSpeak.writeFields(channelID, writeAPIKey);
if(x == 200) {
Serial.println("Data successfully sent to ThingSpeak");
} else {
Serial.println("Failed to send data to ThingSpeak");
}
// Wait 20 seconds before sending the next update
delay(20000);
}