#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <DHT.h>
#define DHTPIN 4 // Pin data sensor DHT22 terhubung ke pin 1
#define DHTTYPE DHT22 // Tipe sensor DHT
const char *ssid = "Wokwi-GUEST";
const char *password = "";
const char *host = "api.thingspeak.com";
const char *apiKey = "JZMHOYH7J03IH33C";
DHT dht(DHTPIN, DHTTYPE);
WiFiClient client;
const int httpPort = 80;
void setup() {
Serial.begin(115200);
delay(10);
// Initialize DHT sensor
dht.begin();
// Connect to WiFi
connectToWiFi();
}
void loop() {
delay(2000); // Minimum 2-second delay between temperature readings
// Read temperature from DHT sensor
float temperature = dht.readTemperature();
if (isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Current temperature: ");
Serial.println(temperature);
// Send data to ThingSpeak
if (sendDataToThingSpeak(temperature)) {
Serial.println("Data sent to ThingSpeak successfully!");
} else {
Serial.println("Failed to send data to ThingSpeak!");
}
}
void connectToWiFi() {
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("");
Serial.println("WiFi connected");
} else {
Serial.println("");
Serial.println("Failed to connect to WiFi. Please check your credentials.");
// You may add additional actions here if needed
}
}
bool sendDataToThingSpeak(float temperature) {
if (client.connect(host, httpPort)) {
String url = "/update?api_key=";
url += apiKey;
url += "&field1=";
url += String(temperature);
url += "\r\n";
Serial.print("Requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
client.stop();
return true;
} else {
Serial.println("Failed to connect to ThingSpeak!");
return false;
}
}