#include <DHTesp.h>
#include <WiFi.h>
#include <ThingSpeak.h>
const char* ssid = "wokwi_GUEST";
const char* pass = "";
WiFiClient client;
unsigned long MyChannelNumber = 2610009;
const char* myWriteAPIKey = "RH2ZXRCZPCG5HA3K";
DHTesp dhtSensor;
const int dhtPin = 27;
const int trig = 17;
const int echo = 16;
int distance;
int duration;
void setup()
{
Serial.begin(115200);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
dhtSensor.setup(dhtPin, DHTesp::DHT22);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
connectToWiFi();
}
void loop()
{
TempAndHumidity data = dhtSensor.getTempAndHumidity();
Serial.print("Humidity: ");
Serial.print(data.humidity);
Serial.print(" Temperature: ");
Serial.print(data.temperature);
Serial.print(" Distance = ");
Serial.println(getDistance());
distance = getDistance();
ThingSpeak.setField(1, distance);
ThingSpeak.setField(2, data.temperature);
ThingSpeak.setField(3, data.humidity);
int statusCode = ThingSpeak.writeFields(MyChannelNumber, myWriteAPIKey);
if (statusCode == 200) {
Serial.println("Channel updated successfully.");
} else {
Serial.println("Problem writing data. HTTP error code: " + String(statusCode));
}
delay(15000);
}
float getDistance()
{
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delay(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
return (duration * 0.034 / 2);
}
void connectToWiFi()
{
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect to WiFi");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("\nConnected to WiFi");
}
}