The Firebase library for the ESP8266 is becoming complex and sometimes using it seems overkill and create lot of headache while we only want to write simple variables to the realtime database. So, in today’s post I will explain how can you use the Firebase real time database in ESP8266 without making it over complex with libraries and simply calling a simple REST API calls.
Get Firebase Real time Database Secrets
It is almost a deprecated way, but works. So you need to find your database secret from your firebase project settings.
- Go to the Firebase console (https://console.firebase.google.com/).
- Select your project.
- Go to the “Project settings” section.
- Scroll down to the “Service Accounts” tab.
- Click on the “Database Secrets” tab.
- Copy the “Database Secret” value.
Arduino Code for Firebase Real time Database Writing
Here is a simple Arduino code for esp8266 nodemcu to write onto the firebase real time database without using any complex library. Here is the complete code.
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
const char* ssid = "project";
const char* password = "project123";
const char* host = "yourdb-default-rtdb.firebaseio.com"; // no "https://"
const char* auth = "your_database_secrects"; // get from DB settings
const int httpsPort = 443;
WiFiClientSecure client;
void setup() {
Serial.begin(115200);
delay(100);
Serial.println("Booting...");
Serial.print("Connecting to WiFi: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
client.setInsecure(); // skip SSL cert check
Serial.println("Connecting to Firebase...");
if (!client.connect(host, httpsPort)) {
Serial.println("Connection to Firebase failed");
return;
}
Serial.println("Connected to Firebase");
String path = "/sensor.json?auth=" + String(auth);
String json = "{\"temp\":25.4,\"status\":\"ok\"}";
Serial.println("Sending PUT request to Firebase...");
client.print(String("PUT ") + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/json\r\n" +
"Content-Length: " + json.length() + "\r\n\r\n" +
json);
Serial.println("Data sent.");
// Optional: print response
while (client.connected() || client.available()) {
String line = client.readStringUntil('\n');
if (line.length()) Serial.println(line);
}
Serial.println("Firebase update done.");
}
void loop() {}
Code language: Arduino (arduino)