#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
#include <LiquidCrystal_I2C.h>
#include <Arduino_JSON.h>
#define DHTPIN 12
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String serverName = "https://monitoring-suhu-dan-kele-699d6-default-rtdb.asia-southeast1.firebasedatabase.app/sensor.json";
String serverName2 = "https://monitoring-suhu-dan-kele-699d6-default-rtdb.asia-southeast1.firebasedatabase.app/actuator.json";
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(19,OUTPUT);
dht.begin();
LCD.init();
LCD.backlight();
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
// put your main code here, to run repeatedly:
String myjson;
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if any reads failed and exit early (to try again).
if (isnan(temperature) || isnan(humidity)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
LCD.setCursor(0, 0);
LCD.print(temperature);
LCD.setCursor(0, 1);
LCD.print(humidity);
Serial.print(F("Humidity: "));
Serial.print(humidity);
Serial.print(F("% Temperature: "));
Serial.print(temperature);
Serial.println(F("°C "));
//ini utk menulis ke firebase
if(WiFi.status()== WL_CONNECTED)
{
HTTPClient http;
http.begin(sensor.json);
int httpResponseCode = http.PUT(myjson);
if (httpResponseCode>0)
{
//Serial.print("HTTP Response code: ");
//Serial.println(httpResponseCode);
//String payload = http.getString();
//Serial.println(payload);
}
else
{
//Serial.print("Error code: ");
//Serial.println(httpResponseCode);
}
http.end();
}
else
{
//Serial.println("WiFi Disconnected");
}
// ini utk membaca dari thingspeak
if(WiFi.status()== WL_CONNECTED)
{
HTTPClient http;
String serverPath = serverName2;
http.begin(serverPath.c_str());
int httpResponseCode = http.GET();
if (httpResponseCode>0)
{
String payload = http.getString();
JSONVar myObject = JSON.parse(payload);
if (JSON.typeof(myObject) == "undefined")
{
Serial.println("Parsing input failed!");
return;
}
JSONVar keys = myObject.keys();
JSONVar value = myObject[keys[4]];
byte databuzzer = atoi(value);
Serial.println(databuzzer);
if(databuzzer==5)
{
tone(19,1000);
Serial.println("bunyi");
}
else
{
noTone(19);
Serial.println("off");
}
}
else
{
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
else
{
Serial.println("WiFi Disconnected");
}
delay(2000);
}