#include <WiFi.h>
#include <HTTPClient.h>
// Wi-Fi credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Firebase project URL and API Key
#define DATABASE_URL "https://hantu-815c4-default-rtdb.asia-southeast1.firebasedatabase.app"
#define API_KEY "AIzaSyBRS2GWYraVW0XVHibGg5EQe1zx7r-5fWU"
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Set initial value in Firebase
sendDataToFirebase("/example/data", 123);
}
void loop() {
// Read the value from Firebase
int value = getDataFromFirebase("/example/data");
Serial.printf("Data: %d\n", value);
delay(2000); // Wait for 2 seconds before reading again
}
void sendDataToFirebase(String path, int value) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(DATABASE_URL) + path + ".json?auth=" + API_KEY;
http.begin(url);
http.addHeader("Content-Type", "application/json");
String payload = String("{\"value\":") + value + "}";
int httpResponseCode = http.PUT(payload);
if (httpResponseCode > 0) {
Serial.printf("HTTP Response code: %d\n", httpResponseCode);
} else {
Serial.printf("Error code: %d\n", httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}
int getDataFromFirebase(String path) {
int value = 0;
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(DATABASE_URL) + path + ".json?auth=" + API_KEY;
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.println(payload);
value = payload.toInt();
} else {
Serial.printf("Error code: %d\n", httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
return value;
}