Skip to content

Instantly share code, notes, and snippets.

@izzuddin91
Created May 28, 2026 13:26
Show Gist options
  • Select an option

  • Save izzuddin91/8b35501d50006b83d081a41096425168 to your computer and use it in GitHub Desktop.

Select an option

Save izzuddin91/8b35501d50006b83d081a41096425168 to your computer and use it in GitHub Desktop.
switch relay on and send data to firestore
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>
#include <time.h>
const char* ssid = "<id>";
const char* password = "<pwd>";
const String FIREBASE_PROJECT_ID = "<id>";
const String API_KEY = "<api_key>";
#define RELAY_PIN D0
WiFiClientSecure client;
// =======================
// CONNECT WIFI
// =======================
void connectWiFi()
{
WiFi.begin(ssid, password);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
// =======================
// INIT INTERNET TIME
// =======================
void initTime()
{
configTime(8 * 3600, 0, "pool.ntp.org", "time.nist.gov");
Serial.print("Waiting for NTP time");
time_t now = time(nullptr);
while (now < 100000)
{
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println("");
Serial.println("Time synchronized");
}
// =======================
// SEND TO FIRESTORE
// =======================
void sendToFirestore(String relayState)
{
HTTPClient https;
client.setInsecure();
String url =
"https://firestore.googleapis.com/v1/projects/" +
FIREBASE_PROJECT_ID +
"/databases/(default)/documents/relay_logs?key=" +
API_KEY;
Serial.println(url);
// Get current timestamp
time_t now = time(nullptr);
Serial.print("Unix Timestamp: ");
Serial.println(now);
if (https.begin(client, url))
{
https.addHeader("Content-Type", "application/json");
String payload =
"{"
"\"fields\": {"
"\"status\": {"
"\"stringValue\": \"" + relayState + "\""
"},"
"\"last_on_timestamp\": {"
"\"integerValue\": \"" + String((long)now) + "\""
"}"
"}"
"}";
Serial.println(payload);
int httpCode = https.POST(payload);
Serial.print("HTTP Response: ");
Serial.println(httpCode);
String response = https.getString();
Serial.println(response);
https.end();
}
else
{
Serial.println("HTTPS connection failed");
}
}
// =======================
// SETUP
// =======================
void setup()
{
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
connectWiFi();
initTime();
}
// =======================
// LOOP
// =======================
void loop()
{
// Relay ON
digitalWrite(RELAY_PIN, HIGH);
Serial.println("Relay ON");
sendToFirestore("ON");
delay(5000);
// Relay OFF
digitalWrite(RELAY_PIN, LOW);
Serial.println("Relay OFF");
delay(3600000); // 1 hour
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment