#include <WiFi.h>
#include <WiFiClient.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <DHTesp.h>
#define DHT_PIN 18
String baseUrl = "http://iotmonitor.nanartp.web.id/api";
String temperatureEndpoint = baseUrl + "/temps";
DHTesp dht;
float temperature, humidity;
float celcius, fahrenheit, kelvin;
void setup() {
Serial.begin(115200);
dht.setup(DHT_PIN, DHTesp::DHT22);
Serial.println("Mulai menghubungkan ke WiFi...");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
Serial.println("Connecting....");
delay(250);
}
Serial.println("Terhubung ke WiFi.");
}
void loop() {
dhtRead();
insertTemperature(temperature);
delay(1000);
// delay(5000);
}
void insertTemperature(float value) {
HTTPClient http;
// menghubungkan ke API
Serial.println("Menghubungkan ke API");
Serial.println(temperatureEndpoint);
http.begin(temperatureEndpoint);
http.addHeader("Content-Type", "Application/json");
DynamicJsonDocument doc(1024);
doc["value"] = value;
String body = "";
serializeJson(doc, body);
// melakukan POST request
int statusCode = http.POST(body);
if (statusCode > 0) {
Serial.println("Berhasil dengan status: " + statusCode);
String payload = http.getString();
Serial.println(payload);
} else {
Serial.println("Terjadi kesalahan " + statusCode);
}
http.end();
}
void getTemperature() {
HTTPClient http;
// menghubungkan ke API
Serial.println("Menghubungkan ke API");
Serial.println(temperatureEndpoint);
http.begin(temperatureEndpoint);
http.addHeader("Content-Type", "Application/json");
// melakukan GET request
int statusCode = http.GET();
Serial.print(statusCode);
if (statusCode > 0) {
Serial.println("Berhasil dengan status: " + statusCode);
String payload = http.getString();
Serial.println(payload);
} else {
Serial.println("Terjadi kesalahan " + statusCode);
}
http.end();
delay(5000);
}