#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <ESP32Servo.h>
// Include helper files
#include "addons/TokenHelper.h"
#include "addons/RTDBHelper.h"
// Wi-Fi credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Firebase credentials
#define API_KEY "AIzaSyCdrlda1jjQ5tb4G6Is4mkIbrSDWyFbw6Q"
#define DATABASE_URL "https://fir-wokwi-3fc2d-default-rtdb.firebaseio.com/" // Must start with https://
// Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
const int LED_PIN = 16; // GPIO16
const int SERVO_PIN = 4; // GPIO17 (change if needed)
Servo myServo;
bool signupOK = false;
void setup() {
Serial.begin(115200);
// LED pin
pinMode(LED_PIN, OUTPUT);
// Servo pin
myServo.attach(SERVO_PIN);
myServo.write(0); // initial position
// Connect to Wi-Fi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println("\nConnected to WiFi");
Serial.println("IP Address: " + WiFi.localIP().toString());
// Firebase configuration
config.api_key = API_KEY;
config.database_url = DATABASE_URL;
config.token_status_callback = tokenStatusCallback;
// Sign up (anonymous)
if (Firebase.signUp(&config, &auth, "", "")) {
Serial.println("Firebase signup OK");
signupOK = true;
} else {
Serial.printf("Firebase signup failed: %s\n", config.signer.signupError.message.c_str());
}
Firebase.begin(&config, &auth);
Firebase.reconnectWiFi(true);
}
void loop() {
if (Firebase.ready() && signupOK) {
// --- LED Control ---
if (Firebase.RTDB.getBool(&fbdo, "/LED")) {
bool ledState = fbdo.boolData();
digitalWrite(LED_PIN, ledState ? HIGH : LOW);
Serial.printf("LED State from Firebase: %s\n", ledState ? "ON" : "OFF");
} else {
Serial.println("Failed to get LED state: " + fbdo.errorReason());
}
// --- Servo Control ---
if (Firebase.RTDB.getBool(&fbdo, "/ServoState")) {
bool servoState = fbdo.boolData();
if (servoState) {
myServo.write(90); // 90 degrees
} else {
myServo.write(0); // 0 degrees
}
Serial.printf("Servo State from Firebase: %s\n", servoState ? "90°" : "0°");
} else {
Serial.println("Failed to get Servo state: " + fbdo.errorReason());
}
delay(2000);
}
}