Blynk RFID IOT Smart Door Lock with esp8266 & RC522

control door lock with blynk and rfid card.

clip

1 Like

Very nice. Can you please add in your images and the code (formatted please :wink: ) into this topic, and perhaps a QR if you wish. That way it is more immersive with this community and not just a redirection link to Youtube or other sites. Thank you.

This code does not want to trigger the elock output, which can be, apparently there is nothing wrong.


/* First part of the code.

IoT based RFID smart door lock system using NodeMCU and Blynk
*/

#include "OTABlynkCredentials.h"

#ifdef ESP8266
#include <BlynkSimpleEsp8266.h>
#elif defined(ESP32)
#include <BlynkSimpleEsp32.h>
#else
#error "Board not found"
#endif
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#define BLYNK_PRINT Serial
credentials Credentials;



//Variables
char auth_token[33];
bool connected_to_internet = 0;
const int Erasing_button = 0; // D3 NodeMCU Pin


//Provide credentials for your ESP server
char* esp_ssid = "IoT";
char* esp_pass = "";

#define elock D0
#define SS_PIN 4
#define RST_PIN 5
#define LED_G 9 //define green LED pin
#define LED_R 10 //define red LED
#define BUZZER 15 //buzzer pin

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
Servo myServo; //define servo name
 
SimpleTimer timer;
int aflag = 0; 
int bflag = 0; 
int cflag = 0;
int dflag = 0;
int eflag = 0;
int fflag = 0;
int gflag = 0;
int hflag = 0;
int iflag = 0;
int jflag = 0;
int lflag = 0;

WidgetTerminal terminal(V2);

void setup()

{

  Serial.begin(115200);
  pinMode(Erasing_button, INPUT);


  for (uint8_t t = 4; t > 0; t--) {
    Serial.println(t);
    delay(1000);
  }

  // Press and hold the button to erase all the credentials
  if (digitalRead(Erasing_button) == LOW)
  {
    Credentials.Erase_eeprom();

  }

  String auth_string = Credentials.EEPROM_Config();
  auth_string.toCharArray(auth_token, 33);

  if (Credentials.credentials_get())
  {

    Blynk.config(auth_token);
    connected_to_internet = 1;

  }
  else
  {
    Credentials.setupAP(esp_ssid, esp_pass);
    connected_to_internet = 0;
  }
  if (connected_to_internet)
  {
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522 RFID 
  myServo.attach(2); //servo pin D4
  myServo.write(0); //servo start position
  pinMode(LED_G, OUTPUT);
  pinMode(LED_R, OUTPUT);
  pinMode(BUZZER, OUTPUT);
  pinMode(elock,OUTPUT);
  digitalWrite(elock, HIGH);
  noTone(BUZZER);
  Serial.println("Place your card on the reader...");
  Serial.println();
  timer.setInterval(1000L, iot_rfid);
  }
}

void loop()
{
  Credentials.server_loops();

  if (connected_to_internet)
  {


   timer.run(); // Initiates SimpleTimer
Blynk.run();   
    
}
}
void iot_rfid()
{
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) 
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) 
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++) 
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], DEC);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], DEC));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();


  // defining cards here
  if( (content.substring(1) == "id card") && (aflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Luciano");
    Blynk.virtualWrite(V2, "Usuário Luciano" );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
 else
 if( (content.substring(1) == "id card") && (bflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Cassia");
    Blynk.virtualWrite(V2, "Usuário Cassia" );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
  else
 if( (content.substring(1) == "id card") && (cflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Larissa");
    Blynk.virtualWrite(V2, "Usuário Larissa " );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
  else
 if( (content.substring(1) == "id card") && (dflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Samuel");
    Blynk.virtualWrite(V2, "Usuário Samuel " );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
  else
 if( (content.substring(1) == "id card") && (eflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Michael");
    Blynk.virtualWrite(V2, "Usuário Michael " );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
  else
 if( (content.substring(1) == "id card") && (fflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Keith");
    Blynk.virtualWrite(V2, "Usuário Keith " );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
  else
 if( (content.substring(1) == "id card") && (gflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Silvana");
    Blynk.virtualWrite(V2, "Usuário Silvana " );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
  else
 if( (content.substring(1) == "id card") && (hflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Cicero");
    Blynk.virtualWrite(V2, "Usuário Cicero " );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
  else
 if( (content.substring(1) == "id card") && (iflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Osvaldo");
    Blynk.virtualWrite(V2, "Usuário Osvaldo " );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
  else
 if( (content.substring(1) == "id card") && (jflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Manuel");
    Blynk.virtualWrite(V2, " Usuário Manuel " );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
  else
 if( (content.substring(1) == "11 88 130 162") && (lflag == 1) ) //change the UID of the card/cards that you want to give access
  {
    Serial.println("Usuário Suelen");
    Blynk.virtualWrite(V2, "Usurio´Suelen " );
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    digitalWrite(elock, HIGH); 
    delay(3000); 
    digitalWrite(elock, LOW);
    tone(BUZZER, 500);
    delay(250);
    noTone(BUZZER);
    digitalWrite(LED_G, LOW);
    
}
 else {
    Serial.println("unregistered user");
    Blynk.virtualWrite(V2, "Usuário não registrado tentando acessar portão pedestre " );
    Serial.println(" Access denied");
    digitalWrite(LED_R, HIGH);
    tone(BUZZER, 300);
    delay(1500);
    digitalWrite(LED_R, LOW);
    noTone(BUZZER);
    digitalWrite(elock, LOW);
  }
}
// in Blynk app writes values to the Virtual Pin 3
BLYNK_WRITE(V3)
{
   aflag = param.asInt(); // assigning incoming value from pin V3 to a variable
 
}
BLYNK_WRITE(V4)
{
   bflag = param.asInt(); // assigning incoming value from pin V4 to a variable
 
}
 
BLYNK_WRITE(V5)
{
   cflag = param.asInt(); // assigning incoming value from pin V5 to a variable
 
}
BLYNK_WRITE(V6)
{
   dflag = param.asInt(); // assigning incoming value from pin V3 to a variable
   
}
BLYNK_WRITE(V7)
{
   eflag = param.asInt(); // assigning incoming value from pin V7 to a variable
 
} 
BLYNK_WRITE(V8)
{
   fflag = param.asInt(); // assigning incoming value from pin V8 to a variable
 
}
BLYNK_WRITE(V9)
{
   gflag = param.asInt(); // assigning incoming value from pin V9 to a variable
  
}  
BLYNK_WRITE(V10)
{
   hflag = param.asInt(); // assigning incoming value from pin V10 to a variable
 
} 
BLYNK_WRITE(V11)
{
   iflag = param.asInt(); // assigning incoming value from pin V11 to a variable
 
}
BLYNK_WRITE(V12)
{
   jflag = param.asInt(); // assigning incoming value from pin V12 to a variable
   
} 
 BLYNK_WRITE(V13)
{
   lflag = param.asInt(); // assigning incoming value from pin V13 to a variable
 
} 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Second part of the code.    
OTABlynkCredentials.cpp
*/

/*!
   file OTABlynkCredentials.h

   This code is made for entering WiFi and Blynk Credentials
   Over the Air using your web browser.


   Written by Sachin Soni for techiesms YouTube channel, with
   contributions from the open source community.

  Visit our channel for more interesting projects
  https://www.youtube.com/techiesms

*/



#include "Arduino.h"
#include "OTABlynkCredentials.h"

AsyncWebServer server(80); // Creating WebServer at port 80
WebSocketsServer webSocket = WebSocketsServer(81); // Creating WebSocket Server at port81

//
// This is the webpage which is hosted on your ESP board 
// and you can access this webpage by going to this address
//               
//                    192.168.4.1
//

char _webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script>
var connection = new WebSocket('ws://'+location.hostname+':81/');

connection.onopen = function () 
{  
connection.send('Connect ' + new Date()); };
 connection.onerror = function (error) 
 {   
  console.log('WebSocket Error ', error);
 };
 connection.onmessage = function (e) 
  {  
    console.log('Server: ', e.data);
  };
  
  function credentials_rec()
{

  var ssid = document.getElementById('ssid_cred').value;
  var pass = document.getElementById('pass_cred').value;
  var auth = document.getElementById('auth_token').value;
  var full_command = '#{"ssid":"'+ ssid +'", "pass":"' +pass +'","auth":"'+ auth +'"}';
  console.log(full_command);
  connection.send(full_command);
  location.replace('http://'+location.hostname+'/submit');
}


  </script

  </head>
  <body>
  <label for="ssid_cred">SSID Name:</label>
  <input type="text" id="ssid_cred"><br><br>
  <label for="pass_cred">Password:</label>
  <input type="text" id="pass_cred"><br><br>
  <lable for="auth_token">Auth Token:</label>
  <input type="text" id="auth_token"><br><br>
   <button type="button" onclick=credentials_rec();>Submit</button>

</body>

</html>


)=====";





void _webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
{

  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\n", num);
      break;
    case WStype_CONNECTED: {
        IPAddress ip = webSocket.remoteIP(num);
        Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

        // send message to client
        webSocket.sendTXT(num, "Connected");
      }
      break;
    case WStype_TEXT:
      Serial.printf("[%u] get Text: %s\n", num, payload);

      if (payload[0] == '#') 
      {
        String message = String((char*)( payload));
        message = message.substring(1);
        Serial.println(message);

        //JSON part
        DynamicJsonDocument doc(1024);
        DeserializationError error = deserializeJson(doc, message);

        String ssid = doc["ssid"];
        String pass = doc["pass"];
        String auth = doc["auth"];
        Serial.println(ssid); Serial.println(pass);


        // Clearing EEPROM
        if (ssid.length() > 0 && pass.length() > 0) {
          Serial.println("clearing eeprom");
          for (int i = 0; i < 100; ++i) {
            EEPROM.write(i, 0);
          }


          // Storing in EEPROM
          Serial.println("writing eeprom ssid:");
          for (int i = 0; i < ssid.length(); ++i)
          {
            EEPROM.write(i, ssid[i]);
            Serial.print("Wrote: ");
            Serial.println(ssid[i]);
          }
          Serial.println("writing eeprom pass:");
          for (int i = 0; i < pass.length(); ++i)
          {
            EEPROM.write(32 + i, pass[i]);
            Serial.print("Wrote: ");
            Serial.println(pass[i]);
          }
          Serial.println("writing eeprom auth token:");
          for (int i = 0; i < auth.length(); ++i)
          {
            EEPROM.write(64 + i, auth[i]);
            Serial.print("Wrote: ");
            Serial.println(auth[i]);
          }
          EEPROM.commit();
          delay(2000);

          //Restarting ESP board
          ESP.restart();
          break;
        }
     }
  }
}



void credentials::Erase_eeprom()
{
  EEPROM.begin(512); //Initialasing EEPROM
  Serial.println("Erasing...");
  Serial.println("clearing eeprom");
    for (int i = 0; i < 100; ++i) 
    {
      EEPROM.write(i, 0);
    }
   EEPROM.commit();
}



String credentials::EEPROM_Config()
{
 EEPROM.begin(512); //Initialasing EEPROM
  Serial.println();
  Serial.println();

  //---------------------------------------- Read eeprom for ssid and pass
  Serial.println("Reading EEPROM");


  for (int i = 0; i < 32; ++i)
  {
    ssid += char(EEPROM.read(i));
  }
  Serial.print("SSID: ");
  Serial.println(ssid);

  for (int i = 32; i < 64; ++i)
  {
    pass += char(EEPROM.read(i));
  }

  Serial.print("Password: ");
  Serial.println(pass);
  String auth_token = "";
  for (int i = 64; i < 100; ++i)
  {
    auth_token += char(EEPROM.read(i));
  }
  Serial.print("Auth Token: ");
  Serial.println(auth_token);
  return auth_token;
}



bool credentials::credentials_get()
{
  if (_testWifi())
  {
    Serial.println("Succesfully Connected!!!");
    return true;
  }
  else
  {
    Serial.println("Turning the HotSpot On");
    return false;
  }
}



void credentials::setupAP(char* softap_ssid, char* softap_pass)
{
  
  WiFi.disconnect();
  delay(100);
  WiFi.softAP(softap_ssid,softap_pass);
  Serial.println("softap");
  _launchWeb();
  Serial.println("Server Started");
   webSocket.begin();
    webSocket.onEvent(_webSocketEvent);
}



bool credentials::_testWifi()
{
  int c = 0;
  Serial.println("Waiting for Wifi to connect");
  char* my_ssid = &ssid[0];
  char* my_pass = &pass[0];

  WiFi.begin(my_ssid, my_pass);
  while ( c < 20 ) {
    if (WiFi.status() == WL_CONNECTED)
    {
      return true;
    }
    delay(500);
    Serial.print("*");
    c++;
  }
  Serial.println("");
  Serial.println("Connect timed out, opening AP");
  return false;
}



// This is the function which will be called when an invalid page is called from client
void notFound(AsyncWebServerRequest *request)
{
  request->send(404, "text/plain", "Not found");
}


void credentials::_createWebServer()
{
server.on("/", [](AsyncWebServerRequest * request) {
  request->send_P(200, "text/html", _webpage);
});

// Send a GET request to <IP>/get?message=<message>
server.on("/submit", HTTP_GET, [] (AsyncWebServerRequest * request) {
  String message;
    message = "Credentials received by ESP board!!!";
   request->send(200, "text/plain", message);
});

server.onNotFound(notFound);
server.begin();
  
}

void credentials::_launchWeb()
{
  Serial.println("");
  Serial.print("SoftAP IP: ");
  Serial.println(WiFi.softAPIP());
  _createWebServer();
  // Start the server

}

void credentials::server_loops()
{ 
     webSocket.loop();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*Third part of the code.
OTABlynkCredentials.h
*/

/*!
 * file OTABlynkCredentials.h
 *
 * This code is made for entering WiFi and Blynk Credentials
 * Over the Air using your web browser.
 * 
 *
 * Written by Sachin Soni for techiesms YouTube channel, with
 * contributions from the open source community.
 *
 *Visit our channel for more interesting projects
 *https://www.youtube.com/techiesms
 *
 */



#ifdef ESP8266
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#else
#error "Board not found"
#endif

#include "Arduino.h"

//
//
//  Install these all libraries to make the project work.
//
//
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include <ArduinoJson.h>
#include <EEPROM.h>


class credentials {
  public:
  bool credentials_get();
  void setupAP(char* softap_ssid, char* softap_pass);
  void server_loops();
  String EEPROM_Config();
  void Erase_eeprom();
  private:
  bool _testWifi(void);
  void _launchWeb(void);
  void _createWebServer(void);
  String ssid = "";
  String pass = "";
};

You already have an active topic on this subject. Dumping your code into this two year old topic isn’t going to result in you getting any additional assistance.

Topic closed.

Pete.