#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#define DHTPIN 15 // Correct definition for the DHT data pin
#define DHTTYPE DHT22 // DHT22 type
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Wokwi-GUEST"; // Your WiFi SSID
const char* password = ""; // Your WiFi password
String baseURL = "https://api.thingspeak.com/update?api_key=87JIILFZ88HY6E9D&field1=";
String field2 = "&field2=";
void connectToWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting...");
}
Serial.println("Connected to WiFi");
}
void makeGETRequest(float temp, float hum) {
String url = baseURL + String(temp) + field2 + String(hum);
Serial.print("Sending GET request to: ");
Serial.println(url);
HTTPClient http;
http.begin(url); // Specify the URL here
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
void setup() {
Serial.begin(115200);
Serial.println("Upload the DHT22 Data on the ThingSpeak Server !!!");
dht.begin();
connectToWiFi();
}
void loop() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
if (isnan(temp) || isnan(hum)) {
Serial.println("Failed to read from DHT sensor!");
} else {
Serial.printf("Weather Temperature: %.2f°C, Humidity: %.2f%%\n", temp, hum);
makeGETRequest(temp, hum);
delay(20000); // ThingSpeak has a minimum 15 seconds wait time, here we use 20 seconds
}
}