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

#include "DHT.h"
#define DHTPIN 26    
#define DHTTYPE DHT22  

const char* WIFI_NAME = "Wokwi-GUEST";  //SSID_hotspot
const char* WIFI_PASSWORD = "";         //pswd_phone_wifi

const int myChannelId = 2684878;    //your channel id
const char* myWriteApiKey = "2VQ2JF9EQZ3S91RS"; //write apikeyof your channel
const char* server = "api.thingspeak.com";

DHT dht(DHTPIN, DHTTYPE);
WiFiClient client;
const int trigPin = 5;
const int echoPin = 18;
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
void anil(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distanceCm = duration * SOUND_SPEED/2;
  distanceInch = distanceCm * CM_TO_INCH;
  Serial.print("Distance (cm): ");
  Serial.println(distanceCm);
  delay(1000);
}



void setup() {
  Serial.begin(115200);
  dht.begin();
  Serial.begin(115200); 
  pinMode(trigPin, OUTPUT); 
  pinMode(echoPin, INPUT); 

  WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED){
    delay(1000);
    Serial.println("Wifi not connected");
  }
  Serial.println("Wifi connected !");
  Serial.println("Local IP: " + String(WiFi.localIP()));
  WiFi.mode(WIFI_STA);
  ThingSpeak.begin(client);
}

void loop() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  ThingSpeak.setField(1,t);
  ThingSpeak.setField(2,h);
  ThingSpeak.setField(3,distanceCm);
  int x = ThingSpeak.writeFields(myChannelId,myWriteApiKey);
  Serial.print("Temperature: \t");
  Serial.println(t);
  Serial.print("Humidity: \t");
  Serial.println(h);
  delay(1000);
  anil();

  
}