#include <Wire.h>
#include <LiquidCrystal.h>
#include <DHT.h>
#include <WiFi.h>
#include <HTTPClient.h>
// Pin definitions
#define DHTPIN 4
#define DHTTYPE DHT22
#define TRIG_PIN 5
#define ECHO_PIN 18 // Mendeklarasikan pin ECHO_PIN
// WiFi credentials
const char *ssid = "Wokwi-GUEST"; // Gantilah dengan SSID WiFi Anda
const char *password = ""; // Gantilah dengan password WiFi Anda
// ThingSpeak settings
const char *serverUrl = "https://api.thingspeak.com/update"; // Gunakan HTTPS
const char *apiKey = "355BB8BN1EDG4II2"; // Gantilah dengan API Key Anda
// ThingSpeak read API settings
const char *readUrl = "https://api.thingspeak.com/channels/2795468/feeds.json?api_key=IJ9ECNXQFCWNM7F7&results=2"; // Gunakan HTTPS
// Sensor and LCD objects
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal lcd(15, 2, 14, 27, 26, 25);
void setup()
{
Serial.begin(115200);
dht.begin();
lcd.begin(16, 2);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT); // Menggunakan ECHO_PIN
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi...");
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20)
{
delay(1000);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED)
{
Serial.println("\nConnected to WiFi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
else
{
Serial.println("\nFailed to connect to WiFi");
}
}
void loop()
{
// Read sensor data
float Humidity = dht.readHumidity();
float Temperature = dht.readTemperature();
// Send data to ThingSpeak
if (WiFi.status() == WL_CONNECTED)
{
WiFiClient client;
HTTPClient http;
String httpRequestUrl = String(serverUrl) + "?api_key=" + apiKey + "&field1=" + String(Temperature) + "&field2=" + String(Humidity);
http.begin(client, httpRequestUrl);
int httpResponseCode = http.GET();
if (httpResponseCode > 0)
{
Serial.println("HTTP Response code: " + String(httpResponseCode));
Serial.println(http.getString());
}
else
{
Serial.println("Error on HTTP GET: " + String(httpResponseCode));
}
http.end();
}
// Read data from ThingSpeak (optional)
readThingSpeakFeed();
delay(30000); // Delay before the next loop
}
void readThingSpeakFeed()
{
if (WiFi.status() == WL_CONNECTED)
{
WiFiClient client;
HTTPClient http;
http.begin(client, readUrl); // Menggunakan HTTPS
int httpResponseCode = http.GET();
if (httpResponseCode > 0)
{
String response = http.getString();
Serial.println("Response from ThingSpeak:");
Serial.println(response);
}
else
{
Serial.println("Error on HTTP GET: " + String(httpResponseCode));
}
http.end();
}
else
{
Serial.println("WiFi not connected");
}
}