Deligence Technologies
Published © LGPL

Over the Air (OTA) Update of NodeMCU (ESP8266) Using MQTT

In this project I'm going to tell you about how to use Over-the-Air (OTA) software update for NodeMCU (ESP8266).

IntermediateProtip3 hours2,712
Over the Air (OTA) Update of NodeMCU (ESP8266) Using MQTT

Things used in this project

Hardware components

RFID reader (generic)
×1
NodeMCU ESP8266 Breakout Board
NodeMCU ESP8266 Breakout Board
×1
Jumper wires (generic)
Jumper wires (generic)
×1
ESP8266 ESP-01
Espressif ESP8266 ESP-01
×1

Story

Read more

Schematics

schematic

This is schematic

Code

Source Code

Arduino
this is Source Code
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include<SoftwareSerial.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <MFRC522.h>

#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

const char* ssid = "Your ssid name";
const char* password = "your ssid password";
int led = 16;
int flash = 0;

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                   // use 8883 for SSL
#define AIO_USERNAME    "Your Adafruit AIO Key"
#define AIO_KEY         "Your Adafruit AIO Password"
#define SS_PIN 2 //FOR RFID SS PIN BECASUSE WE ARE USING BOTH ETHERNET SHIELD AND RS-522
#define RST_PIN 15
#define No_Of_Card 3

bool flag =0; // For selecting Mode

WiFiClient client;

Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
Adafruit_MQTT_Subscribe Bulb1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Bulb1");
void MQTT_connect();

char server[] = "192.168.0.111";   //eg: 192.168.0.222

SoftwareSerial mySerial(8,9);     
MFRC522 rfid(SS_PIN,RST_PIN);
MFRC522::MIFARE_Key key; 
byte id[No_Of_Card][4]={
  {44,153,22,219},             //RFID NO-1
  {112,224,72,84},             //RFID NO-2
  {151,94,80,84}              //RFID NO-3
};
byte id_temp[3][3];
byte i;
int j=0;







void setup() {
  pinMode(led,OUTPUT);
  pinMode(flash,INPUT);

  pinMode(5,OUTPUT);
  Serial.begin(115200);
  Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  //ArduinoOTA.setHostname("My ESP");

  // No authentication by default
  // ArduinoOTA.setPassword((const char *)"123"); // password

  ArduinoOTA.onStart([]() {
    digitalWrite(led,HIGH);
    Serial.println("Start");
  });
  ArduinoOTA.onEnd([]() {
    digitalWrite(led,LOW);
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  mqtt.subscribe(&Bulb1);


SPI.begin();
  rfid.PCD_Init();

    for(byte i=0;i<6;i++)
  {
    key.keyByte[i]=0xFF;
  }

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
 
  // Start the server
//  server.begin();
  Serial.println("Server started");
  Serial.print(WiFi.localIP());
  delay(1000);
  Serial.println("connecting...");



  
}



void loop() {

  MQTT_connect();

Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(10))) {
   
    if (subscription == &Bulb1) {
      Serial.print(F("Got_Bulb1: "));
      Serial.println((char *)Bulb1.lastread);
      uint16_t num = atoi((char *)Bulb1.lastread);
      flag= num;
    }
  }

  
  if(flag==1) // OTA mode
  ArduinoOTA.handle();
  
  else // normal mode
  {
    abc();
    
  }
  

}

void abc()
{

 // Check if a client has connected
  int m=0;
  if(!rfid.PICC_IsNewCardPresent())
  return;
  if(!rfid.PICC_ReadCardSerial())
  return;
  for(i=0;i<4;i++)
  {
   id_temp[0][i]=rfid.uid.uidByte[i]; 
             delay(50);
  }
  
   for(i=0;i<No_Of_Card;i++)
  {
          if(id[i][0]==id_temp[0][0])
          {
            if(id[i][1]==id_temp[0][1])
            {
              if(id[i][2]==id_temp[0][2])
              {
                if(id[i][3]==id_temp[0][3])
                {
                  Serial.print("your card no :");
                  for(int s=0;s<4;s++)
                  {
                    Serial.print(rfid.uid.uidByte[s]);
                    Serial.print(" ");
                   
                  }
                  Serial.println("\nVALID");
                  Sending_To_DB();
                  j=0;
                            
                            rfid.PICC_HaltA(); rfid.PCD_StopCrypto1();   return; 
                }
              }
            }
          }
   else
   {j++;
    if(j==No_Of_Card)
    {
      Serial.println("inVALID");
      Sending_To_DB();
      j=0;
    }
   }
  }
  
     // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();

}

void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}

void Sending_To_DB()   //CONNECTING WITH MYSQL
 {
   if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    Serial.println("GET /rfid/rfid_read.php?allow=");     //YOUR URL /rfid/rfid_read.php?allow
    client.print("GET /rfid/nodemcu_rfid/rfid_read.php?allow=");     //YOUR URL /rfid/rfid_read.php?allow  /var/www/html/rfid/rfid_read.php
    if(j!=No_Of_Card)
    {
      Serial.println('1');
      client.print('1');
    }
    else
    {
      Serial.println('0');
      client.print('0');
    }
    Serial.println("&id=");
    client.print("&id=");
    for(int s=0;s<4;s++)
                  {
                    Serial.println(rfid.uid.uidByte[s]);
                    client.print(rfid.uid.uidByte[s]);
                                  
                  }
    client.print(" ");      //SPACE BEFORE HTTP/1.1
    client.print("HTTP/1.1");
    client.print("Host: ");
     client.println(server);
    client.println("Host: 192.168.0.111");//eg: 192.168.0.222
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  client.stop();
 }

Credits

Deligence Technologies

Deligence Technologies

7 projects • 84 followers
IoT & Embedded Development team

Comments