#include <WiFi.h>
#include <ThingSpeak.h>
#include "DHTesp.h"
DHTesp dhtSensor;
TempAndHumidity data;
const int DHT_PIN=15;
char ssid[]="Wokwi-GUEST";
char pass[]="";
WiFiClient Client;
unsigned long myChannelNumber=2078954;
const char * myWriteAPIKey="GKAFZ5PTWO3MQJZN";
const int trig=14;
const int echo=12;
long duration;
long distance;
int statusCode;
void setup()
{
Serial.begin(115200);
dhtSensor.setup(DHT_PIN ,DHTesp::DHT22);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(Client);
}
void loop()
{
data=dhtSensor.getTempAndHumidity();
Serial.println("Humidity:"+String(data.humidity));
Serial.println("Temperature:"+String(data.temperature));
Serial.println("-------------");
delay(1000);
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(30);
digitalWrite(trig, LOW);
duration=pulseIn(echo,HIGH);
distance=(duration*0.034/2)+1;
Serial.println("distance: "+String(distance));
if(WiFi.status() !=WL_CONNECTED)
{
Serial.print("Attempting to connect");
while(WiFi.status() !=WL_CONNECTED)
{
WiFi.begin(ssid,pass);
Serial.print(".");
delay(5000);
}
Serial.println("\nConected.");
ThingSpeak.setField(1,data.humidity);
ThingSpeak.setField(2,data.temperature);
ThingSpeak.setField(3,distance);
statusCode=ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);
if(statusCode==200)
{
Serial.println("Channel update successfull.");
}
else
{
Serial.println("Problem writing data. HTTP error code:"+String(statusCode));
}
delay(15000);
}
}