#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST"; // Nama jaringan WiFi yang akan dihubungkan
const char* password = "";
// Replace with your ThingsBoard device token
const char* token = "w6uYaA0WP3GlbN2GOpn7";
const char* server = "http://thingsboard.cloud"; // or your own ThingsBoard server URL
void setup() {
Serial.begin(115200);
delay(10);
// Initialize random seed
randomSeed(analogRead(0));
// Connect to Wi-Fi
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { // Check Wi-Fi connection status
HTTPClient http;
// Generate random telemetry data
float temperature = random(200, 300) / 10.0; // Random temperature between 20.0 and 30.0
float humidity = random(300, 800) / 10.0; // Random humidity between 30.0 and 80.0
// Create JSON payload
DynamicJsonDocument doc(1024);
doc["temperature"] = temperature;
doc["humidity"] = humidity;
String payload;
serializeJson(doc, payload);
// Send telemetry data
String url = String(server) + "/api/v1/" + token + "/telemetry";
http.begin(url);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
String response = http.getString(); // Get the response to the request
Serial.println(httpResponseCode); // Print return code
Serial.println(response); // Print request answer
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end(); // Free resources
delay(5000); // Send data every 5 seconds
} else {
Serial.println("WiFi Disconnected");
}
}