#include <WiFi.h>
#include "DHT.h"
#include "ThingSpeak.h"
#define DHTPIN 15
#define DHTTYPE DHT22
#define LEDPIN 33
#define POTPIN 34
const char* ssid = "Wokwi-GUEST";
const char* password = "";
unsigned long channelID = 2231178; // set your real channel ID here
const char* writeAPIKey = "44G9HY60Q65XRSWC"; // set your real write API key here
DHT dht(DHTPIN, DHTTYPE);
WiFiClient client;
void setup() {
Serial.begin(115200);
while(!Serial){} // wait for serial (safe in some environments)
Serial.println("Starting diagnostic...");
pinMode(LEDPIN, OUTPUT);
pinMode(POTPIN, INPUT);
dht.begin();
// Connect WiFi
Serial.print("Connecting to WiFi ");
WiFi.begin(ssid, password);
unsigned long wifiStart = millis();
while (WiFi.status() != WL_CONNECTED && millis() - wifiStart < 15000) {
Serial.print(".");
delay(500);
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nWiFi connected. IP: " + WiFi.localIP().toString());
} else {
Serial.println("\nWiFi connection FAILED (timeout). Check Wokwi WiFi or SSID.");
}
// Initialize ThingSpeak client
ThingSpeak.begin(client);
}
void loop() {
// Read DHT
float temp = dht.readTemperature();
float hum = dht.readHumidity();
// Read POT as simulated heart rate
int pot = analogRead(POTPIN);
int heartRate = map(pot, 0, 4095, 60, 120);
// Print sensor status
if (isnan(temp) || isnan(hum)) {
Serial.println("[DIAG] DHT error: temp or hum = NaN");
} else {
Serial.printf("[DIAG] Temp = %.2f C, Humidity = %.2f %%\n", temp, hum);
}
Serial.printf("[DIAG] Pot=%d → HeartRate ~ %d BPM\n", pot, heartRate);
// Local alert check (no upload yet)
bool alert = (!isnan(temp) && temp > 37.0) || heartRate > 100;
digitalWrite(LEDPIN, alert ? HIGH : LOW);
Serial.printf("[DIAG] Alert: %s | LED set %s\n", alert ? "YES" : "NO", alert ? "HIGH" : "LOW");
// Try upload to ThingSpeak (only if WiFi connected)
if (WiFi.status() == WL_CONNECTED) {
ThingSpeak.setField(1, isnan(temp) ? -999 : temp);
ThingSpeak.setField(2, isnan(hum) ? -999 : hum);
ThingSpeak.setField(3, heartRate);
int response = ThingSpeak.writeFields(channelID, writeAPIKey);
Serial.printf("[DIAG] ThingSpeak writeFields response = %d\n", response);
if (response == 200) Serial.println("[DIAG] Upload OK");
else {
Serial.println("[DIAG] Upload failed:");
// print some helpful info
if (response == 0) Serial.println(" -- No response from ThingSpeak (check network).");
else if (response == 401) Serial.println(" -- Not authorized (check API key).");
else if (response == 404) Serial.println(" -- Channel not found (check channel ID).");
else Serial.println(" -- HTTP code: " + String(response));
}
} else {
Serial.println("[DIAG] Skipping ThingSpeak upload (no WiFi).");
}
Serial.println("-------------------------------------------------");
delay(20000); // wait 20s (ThingSpeak friendly)
}