#include <DHTesp.h>
#include <WiFi.h>
#include <ThingSpeak.h>

char ssid[]="Wokwi-GUEST";
char pass[]="";
WiFiClient client;

unsigned long myChannelNumber= 2073810;
const char* myWriteAPIKey="IBN7TVIDOCOU11X0";
int statusCode;


const int trigpin=2;
const int echopin=4;
float duration;
int distance;
DHTesp dhtsensor;
TempAndHumidity data;
const int dht_pin=15;
void setup() {
  Serial.begin(115200);
  pinMode(trigpin, OUTPUT);
  pinMode(echopin, INPUT);
  dhtsensor.setup(dht_pin,DHTesp::DHT22);

  WiFi.mode(WIFI_STA);
  ThingSpeak.begin(client);
}

void loop() {
  digitalWrite(trigpin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigpin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigpin, LOW);
  duration = pulseIn(echopin, HIGH);
  distance = duration * 0.034/2;
  Serial.println(distance);
  data=dhtsensor.getTempAndHumidity();
 Serial.println("humidity: "+String(data.humidity));
 Serial.println("Temperature: "+String(data.temperature));
 delay(1000);
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("\nConnected");


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 successful");
  }
  else
  {
    Serial.println("Problem Writing data: HTTp error code:"+String(statusCode));
  }
  delay(15000);
}