#include <WiFi.h>
#include <HTTPClient.h>
#include "DHTesp.h"
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
DHTesp dhtSensor;
const int DHT_PIN = 15;
float temperature;
float humidity;
// Replace with your unique IFTTT URL resource
const char* resource = "https://maker.ifttt.com/trigger/BacaanDHT/with/key/hcOx_xk-POfHLy8fQVgFTeHb62c2fiB6-a9csr96jqH";
// Maker Webhooks IFTTT
const char* server = "maker.ifttt.com";
// Previous temperature and humidity readings
float prevTemperature = 0;
float prevHumidity = 0;
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
}
void loop() {
// Get the current temperature and humidity readings
TempAndHumidity data = dhtSensor.getTempAndHumidity();
temperature = data.temperature;
humidity = data.humidity;
// Check if the readings have changed
if (temperature != prevTemperature || humidity != prevHumidity) {
// Update the previous readings
prevTemperature = temperature;
prevHumidity = humidity;
// Send data to IFTTT service
makeIFTTTRequest();
}
delay(1000);
}
// Make an HTTP request to the IFTTT web service
void makeIFTTTRequest() {
Serial.print("Connecting to ");
Serial.print(server);
WiFiClient client;
int retries = 5;
while(!client.connect(server, 80) && (retries-- > 0)) {
Serial.print(".");
}
Serial.println();
if(!client.connected()) {
Serial.println("Failed to connect...");
}
Serial.print("Request resource: ");
Serial.println(resource);
// Format the JSON object with the temperature and humidity readings
String temp = String(temperature, 2) + "°C";
String hum = String(humidity, 1) + "%";
String jsonObject = String("{\"value1\":\"") + temp + "\",\"value2\":\"" + hum + "\"}";
client.println(String("POST ") + resource + " HTTP/1.1");
client.println(String("Host: ") + server);
client.println("Connection: close\r\nContent-Type: application/json");
client.print("Content-Length: ");
client.println(jsonObject.length());
client.println();
client.println(jsonObject);
int timeout = 5 * 10; // 5 seconds
while(!client.available() && (timeout-- > 0)){
delay(100);
}
if(!client.available()) {
Serial.println("No response...");
}
while(client.available()){
Serial.write(client.read());
}
Serial.println("\nclosing connection");
client.stop();
}