Here sharing a ESP8266 (Using Nodemcu) ariuno program to controller a motor over internet using firebase.
In below example as i am controller a motor that have a capacitor so as i ON Motor (RelayStart =13) program should ON a capacitor (RelayCapaciter=14) for 3 second then Off it.
Below code have i wifi configuration page where you can enter your wifi router SSID and password. Follow below steps:
1- First paste your firebase Host and Auth key in code.
2- Connect Nodemcu GPIO pin 13 to Relay (Motor) ON.
3- Connect Nodemcu GPIO pin 14 to RelayCapaciter (for capacitor).
4- Now burn the code in node mcu 8266.
5- To configure your router ssid password. Press Flash button of nodemcu for 3 to 5 seconds. It will enable esp to AP mode and you can get a wifi network with name of ESP-TEST.
6- Connect to this Access Point.
7- Now open borwser and type 192.168.4.1 and you will get a page to enter SSID and Password of your router.
8- Finally click on Submit. Now it has been successfullly connected to your router.
9- Now open your firebase account and you will get two veriable in firebase database. MotorCommand and MotorStatus. Enter ON in MotorCommand it will on the ESP (Motor) as motor on ESP will write back the ON status to MotorStatus variable at firebase.
10- Done.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include "FirebaseESP8266.h"
#include <ESP8266mDNS.h>
#include <ArduinoJson.h>
#include <EEPROM.h>
//------------------ Variables--------------------------
int statusCode;
String ssid = "";
String passphrase = "";
String st;
String content;
const int triggerPin = 0;
bool IN_ST_MODE_FLAGE = true;
bool IN_AP_MODE_FLAGE = false;
int c = 0;
int Current_Gate_Status;
int Last_Gate_Status;
const int RelayStart = 13; //On-off
const int RelayCapaciter = 14; // for capacitor
String Last_Status = "OFF";
unsigned long triggerStartTime = 0; // Variable to store the start time of trigger pin low state
//======================= ON NET =========================================
#define FIREBASE_HOST "Paste you firebase host"
#define FIREBASE_AUTH "Paster your firebase Auth key"
FirebaseData fbdo;
unsigned long sendDataPrevMillis = 0;
String commandpath = "/MotorCommand";
String currentStatusPath = "/MotorStatus";
uint16_t count = 0;
void printResult(FirebaseData &data);
ESP8266WebServer server(80);
void setup()
{
Serial.begin(115200);
pinMode(triggerPin, INPUT);
pinMode(RelayCapaciter,OUTPUT);
pinMode(RelayStart,OUTPUT);
digitalWrite(RelayStart, HIGH);
digitalWrite(RelayCapaciter, HIGH);
//Serial.println();
//Serial.println("Disconnecting previously connected WiFi");
WiFi.disconnect();
EEPROM.begin(512);
//Serial.println();
//Serial.println("Startup");
//Serial.println("Reading EEPROM ssid");
String esid;
for (int i = 0; i < 32; ++i) {
esid += char(EEPROM.read(i));
}
//Serial.println();
Serial.print("SSID: ");
Serial.println(esid);
//Serial.println("Reading EEPROM pass");
String epass = "";
for (int i = 32; i < 96; ++i) {
epass += char(EEPROM.read(i));
}
//Serial.print("PASS: ");
//Serial.println(epass);
WiFi.mode(WIFI_STA);
// WiFi.forceSleepWake(); // Ensure it's awake set it before wifi.begin()
// WiFi.setSleepMode(WIFI_NONE_SLEEP); // Disable sleep mode
if(ssid!="")
WiFi.begin(ssid, passphrase);
else
WiFi.begin(esid, epass);
if (waitForWiFiConnection())
{
Serial.println("Connected to WiFi");
Serial.println(WiFi.localIP());
}
else
Serial.println("Failed to connect to WiFi");
ESP.wdtEnable(10000); //set watchdog timer for 10 second
firebaseConnect(); //connecting to firebase
}
void firebaseConnect()
{
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
fbdo.setBSSLBufferSize(1024, 1024);
fbdo.setResponseSize(1024);
if (!Firebase.beginStream(fbdo, commandpath))
{
Serial.println("------------------------------------");
Serial.println("Can't begin stream connection...");
Serial.println("REASON: " + fbdo.errorReason());
Serial.println("------------------------------------");
Serial.println();
}
Firebase.setString(fbdo, commandpath , String("OFF"));
Firebase.setString(fbdo, currentStatusPath , String("OFF"));
}
void loop()
{
ESP.wdtFeed();
//Serial.println(ESP.getFreeHeap());
//===============================================================================
if (IN_ST_MODE_FLAGE == true) //Current ST MODE
{
if (digitalRead(triggerPin) == LOW)
{
if (triggerStartTime == 0)
{ // If trigger pin just went low, start the timer
triggerStartTime = millis();
Serial.println("Trigger Pin Low");
}
else
if (millis() - triggerStartTime >= 3000)
{ // If trigger/flash button pressed more than 3 seconds than move to AP mode
WiFi.disconnect();
WiFi.softAP("GateController", ""); // Fixed AP name
IN_ST_MODE_FLAGE = false;
IN_AP_MODE_FLAGE = true;
Serial.println("Switched to AP mode");
}
}
else
triggerStartTime = 0; // Reset the timer if trigger pin goes high
if (WiFi.status() != WL_CONNECTED && IN_ST_MODE_FLAGE == true)
Serial.println("Not connected to WiFi");
if (!fbdo.httpConnected() && IN_ST_MODE_FLAGE == true)
{
Serial.println("Unable to connect firebase"); // if firebase connection failed then reconnect
firebaseConnect(); //reconnect to firebase;
}
/* if (!checkInternetConnection()) //check Internet working or not
Serial.println("No Internet.");
else
Serial.println("Internet Connected."); */
if (WiFi.status() == WL_CONNECTED && IN_ST_MODE_FLAGE == true)
{
String State = (fbdo.stringData());
if( State == "ON" && Last_Status=="OFF")
{
// Serial.print("--State ");
// Serial.println(State);
digitalWrite(RelayStart, LOW);
digitalWrite(RelayCapaciter, LOW);
delay(3000);
digitalWrite(RelayCapaciter, HIGH);
Last_Status="ON";
Firebase.setString(fbdo, currentStatusPath , String("ON"));
}
else
{
if( State == "OFF" && Last_Status=="ON")
{
//Serial.print("--State ");
// Serial.println(State);
digitalWrite(RelayStart, HIGH);
Last_Status="OFF";
Firebase.setString(fbdo, currentStatusPath , String("OFF"));
}
}
if (!Firebase.readStream(fbdo)){}
if (fbdo.streamAvailable()){}
}
}
//------------------------------------------------------------------------------
if (IN_ST_MODE_FLAGE == false) // Current AP MODE
{
//waitForWiFiConnection();
if (IN_AP_MODE_FLAGE == true)
{
Serial.println("IN AP Mode ");
launchWeb();
setupAP();
IN_AP_MODE_FLAGE = false; // Wapable lonnched
}
server.handleClient();
}
delay(10);
}
//===============================================================================
bool waitForWiFiConnection()
{
int c = 0;
//Serial.println("Waiting for WiFi to connect");
while (c < 80) {
if (WiFi.status() == WL_CONNECTED)
{
IN_ST_MODE_FLAGE = true;
return true;
}
delay(500);
Serial.print("*");
c++;
}
//Serial.println("\nWiFi connection timed out");
return false;
}
void handleRoot()
{
IPAddress ip = WiFi.softAPIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
content = "<!DOCTYPE HTML>\r\n<html>ESP8266 WiFi Connectivity Setup ";
content += "<form action=\"/scan\" method=\"POST\"><input type=\"submit\" value=\"scan\"></form>";
content += ipStr;
content += "<p>";
content += st;
content += "</p><form method='get' action='setting'><label>SSID: </label><input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
content += "</html>";
server.send(200, "text/html", content);
}
void setupAP()
{
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
//Serial.println("Scan completed");
if (n == 0)
Serial.println("No WiFi Networks found");
else {
//Serial.print(n);
Serial.println(" Networks found");
for (int i = 0; i < n; ++i) {
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
delay(10);
}
}
//Serial.println("");
st = "<ol>";
for (int i = 0; i < n; ++i) {
st += "<li>";
st += WiFi.SSID(i);
st += " (";
st += WiFi.RSSI(i);
st += ")";
st += (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*";
st += "</li>";
}
st += "</ol>";
delay(100);
WiFi.softAP("ESP-TEST", ""); // Set your desired AP name
//Serial.println("Initializing WiFi access point");
launchWeb();
//Serial.println("Over");
}
void handleSetting() {
String qsid = server.arg("ssid");
String qpass = server.arg("pass");
if (qsid.length() > 0 && qpass.length() > 0) {
//Serial.println("Clearing EEPROM");
for (int i = 0; i < 96; ++i) {
EEPROM.write(i, 0);
}
//Serial.println(qsid);
//Serial.println("");
//Serial.println(qpass);
//Serial.println("");
//Serial.println("Writing EEPROM ssid:");
for (int i = 0; i < qsid.length(); ++i) {
EEPROM.write(i, qsid[i]);
//Serial.print("Wrote: ");
//Serial.println(qsid[i]);
}
//Serial.println("Writing EEPROM pass:");
for (int i = 0; i < qpass.length(); ++i) {
EEPROM.write(32 + i, qpass[i]);
//Serial.print("Wrote: ");
//Serial.println(qpass[i]);
}
EEPROM.commit();
content = "{\"Success\":\"Saved to EEPROM... Reset to boot into new WiFi\"}";
statusCode = 200;
ESP.reset();
} else {
content = "{\"Error\":\"404 not found\"}";
statusCode = 404;
//Serial.println("Sending 404");
}
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(statusCode, "application/json", content);
}
void handleScan() {
content = "<!DOCTYPE HTML>\r\n<html><a href='/'>Go back</a></html>";
server.send(200, "text/html", content);
}
bool checkInternetConnection() {
WiFiClient client;
return client.connect("8.8.8.8", 53); // Try to connect to Google's DNS
}
void launchWeb() {
//Serial.println("");
if (WiFi.status() == WL_CONNECTED)
Serial.println("WiFi connected");
//Serial.print("Local IP: ");
//Serial.println(WiFi.localIP());
//Serial.print("SoftAP IP: ");
//Serial.println(WiFi.softAPIP());
server.on("/", HTTP_GET, handleRoot);
server.on("/scan", HTTP_GET, handleScan);
server.on("/setting", HTTP_GET, handleSetting);
server.begin();
//Serial.println("Server started");
}