#include <WiFi.h>
#include<DHT.h>
#define DHTPIN A0
#define DHTTYPE DHT11
#define SSID "Galaxy A327A1B"
#define PASS "123456978"
#define WRITE_API_KEY "CYM5VEHWE0PI8QZF"
#define READ_API_KEY "P4FGD3FA3TZ6K2PW"
#define CHANNEL_ID "2707343"
#define THINGSPEAK_URL "api.thingspeak.com"
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(SSID, PASS);
Serial.print("Connecting to WiFi");
unsigned long startAttemptTime = millis();
while (WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < 10000) {
delay(500);
Serial.print(".");
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nConnected to WiFi");
} else {
Serial.println("\nFailed to connect to WiFi");
}
}
void sendDataToThingSpeak(float temp, float hum) {
String url = "/update?api_key=" + String(WRITE_API_KEY) + "&field1=" + String(temp) +
"&field2=" + String(hum);
Serial.print("Sending data: ");
Serial.println(url);
WiFiClient client;
if (client.connect(THINGSPEAK_URL, 80)) {
client.print("GET " + url + " HTTP/1.1\r\n");
client.print("Host: " THINGSPEAK_URL "\r\n");
client.print("User-Agent: ESP32Client\r\n");
client.print("Connection: close\r\n\r\n");
while (client.available() == 0) {
delay(100);
}
while (client.available()) {
String line = client.readStringUntil('\n');
Serial.println(line);
}
} else {
Serial.println("Connection failed");
}
client.stop(); // Close the connection
}
void loop() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
if (isnan(temp) || isnan(hum)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
sendDataToThingSpeak(temp, hum);
delay(20000);
}