#include <WiFi.h>  
#include <DHT.h>  
  
// Define pin and type for the DHT sensor  
#define DHTPIN 15   
#define DHTTYPE DHT22  
  
// Initialize the DHT sensor  
DHT dht(DHTPIN, DHTTYPE);  
  
const char* ssid = "Wokwi-GUEST"; //Wifi connect  
const char* password = "";  
const char* server = "api.thingspeak.com";  
const String apiKey = "M5N1USS3FYFDH28C"; // API key  
  
WiFiClient client;  
  
void setup() {  
  Serial.begin(115200);  
  dht.begin();  
  connectToWiFi();  
}  
  
void loop() {  
  delay(100);   
  
  // Read humidity and temperature  
  float humidity = dht.readHumidity();  
  float tempC = dht.readTemperature(); // Celsius  
  float tempF = dht.readTemperature(true); // Fahrenheit  
  
  // Check if any reads failed  
  if (isnan(humidity) || isnan(tempC) || isnan(tempF)) {  
    Serial.println("Failed to read from DHT sensor!");  
    return;  
  }  
  
  // Create the data string  
  String postData = "field1=" + String(tempC) + "&field2=" + String(humidity);  
  
  // Send data to ThingSpeak  
  sendDataToThingSpeak(postData);  
  
  // Print the results to the serial monitor  
  Serial.printf("Humidity: %.1f%%  Temperature: %.1f°C %.1f°F\n",  
                 humidity, tempC, tempF);  
}  
  
void connectToWiFi() {  
  Serial.println("Connecting to Wi-Fi...");  
  WiFi.begin(ssid, password);  
  while (WiFi.status() != WL_CONNECTED) {  
    delay(1000);  
    Serial.println("Connecting to WiFi...");  
  }  
  Serial.println("Connected to WiFi");  
}  
  
void sendDataToThingSpeak(String data) {  
  if (client.connect(server, 80)) {  
    Serial.println("Connected to ThingSpeak");  
  
    String url = "/update?api_key=" + apiKey;  
    String headers = "POST " + url + " HTTP/1.1\r\n" +  
                     "Host: " + String(server) + "\r\n" +  
                     "Connection: close\r\n" +  
                     "Content-Type: application/x-www-form-urlencoded\r\n" +  
                     "Content-Length:" + String(data.length()) + "\r\n\r\n";  
  
    client.print(headers);  
    client.print(data);  
  
    // Check HTTP response  
    while (client.connected()) {  
      String line = client.readStringUntil('\r');  
      Serial.print(line);  
    }  
  
    client.stop();  
    Serial.println("Data sent to ThingSpeak");  
  } else {  
    Serial.println("Failed to connect to ThingSpeak");  
  }  
}