#include "DHTesp.h"
#include <WiFi.h>
#include <ThingSpeak.h>
char ssid[] = "Wokwi-GUEST";
// your network SSID (name)
char pass[] = "";
WiFiClient client;
unsigned long myChannelNumber = 2092321;
const char * myWriteAPIKey = "52Z4F3IP9K3LS1MC";
DHTesp dhtsensor;
TempAndHumidity data;
const int pin=15;
const int tri=13;
const int eco=12;
long dur;
float dis;
int statusCode;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
dhtsensor.setup(pin,DHTesp::DHT22);
pinMode(tri,OUTPUT);
pinMode(eco, INPUT);
}
void loop() {
if(WiFi.status() != WL_CONNECTED)
{
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED)
{
WiFi.begin(ssid,pass);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}
data=dhtsensor.getTempAndHumidity();
dis=getdistanceIn();
Serial.println("Distance:"+String(dis));
Serial.println("Temperature"+String(data.temperature,1));
Serial.println("Humidity"+String(data.humidity,2));
Serial.println("___");
ThingSpeak.setField(1,dis);
ThingSpeak.setField(2,data.temperature);
ThingSpeak.setField(3,data.humidity);
statusCode = ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);
if(statusCode == 200) { //successful writing code
Serial.println("Channel update successful.");
}
else {
Serial.println("Problem Writing data. HTTP error code :" + String(statusCode));
}
delay(15000); // data to be uploaded every 15secs
}
long getdistanceIn()
{
digitalWrite(tri, LOW);
delayMicroseconds(2);
digitalWrite(tri, HIGH);
delay(10);
digitalWrite(tri, LOW);
dur=pulseIn(eco,HIGH);
return((dur*0.034/2)+1);
}