rfid fritzing
Internet of Things,  Tutorials

Connecting RFID Scanner to PHP using NodeMcu Wifi Module

In this tutorial, we will learn how to connect your RFID RC522 to your PHP Apps with the use of NodeMcu ESP12.

This tutorial covers how to set up the RFID. You will also learn how to connect RFID to PHP and insert data to Mysql database.

 

Video Demonstration

Requirements

NodeMcu Wifi Module
RFID-RC522
Arduino RFID Library for MFRC522 (SPI)
Arduino IDE
Arduino Core for NodeMCU ESP-12E Using Arduino Boards Manager
Led Lights
220 Ohm to 1000 ohm resistor
Jumper Wires

XAMPP
Download Sourcecode here: NodeMcu,RFID, PHP Source Code (7355 downloads)

 

After preparing the requirements, connect your RFID RC522 to your NodeMcu. Follow the diagram below.

Connection

rfid fritzing

RFIDNodeMcu
3.3V3.3V
RSTD2
GNDGND
MISOD6
MOSID7
SCKD5
SDAD4

 The Yellow light will serve as an indicator that we have successfully connected to wifi.  Green indicates that the request to the server has been sent successfully. Red light indicates that our HTTP request failed / our server did not return “success”.

Led PinNodeMcu
Led w/ 220ohm Resistor (Red)D0
Led w/ 220ohm Resistor (Green)D1
Led w/ 220ohm Resistor (Yellow)D8

 

Setting up Arduino and adding RFID Library

We need to add esp8266 to our Arduino IDE. Open up your IDE then go to “File -> Preferences” or simply hit “Ctrl + comma”

Paste http://arduino.esp8266.com/stable/package_esp8266com_index.json in additional board manager URLs. 

Go to “Tools -> Board -> Boards Manager” search and install esp8266

 

Close and restart your Arduino IDE

Plug in your NodeMcu to your computer. You will notice that your RFID scanner will light up.

 

Selecting Port and Board

Go to Tools -> Port and select the COM Port of your NodeMCU. If you are not sure what port your NodeMcu is plugged in, go to Device Manager -> Ports (COM & LPT)

Now select NodeMcu 1.0 (ESP-12E Module) by clicking Tools -> Board. Scroll down until you find it.

 

Extracting MFRC522 Library

Extract the MFRC522 library to your Arduino Libraries folder. The libraries folder is located in C:\Program Files (x86)\Arduino. (Assuming it is the installation path of your Arduino IDE).

Restart your Arduino IDE

 

Modifying the Codes

Open up the codes attached in Arduino IDE. Change the following lines of code.
Since our RFID Scanner will be wireless, we need a way to transmit the data to our web server. Our NodeMcu will automatically connect to your wifi.

We will send the decimal value of our card uuid to our server by sending a POST request. The URL must be changed to where you deployed our PHP codes. I run XAMPP on my computer. I inputted my LAN IP address.

In our connect.php file in RFID folder. Change the following database credentials.

After modifying the codes, plugin your NodeMCU, and on Arduino ID, click the upload button.


Deploying our PHP Web App

Start your Apache and Mysql in XAMPP Control Panel. Copy paste the rfid folder provided in your htdocs folder. Create a new database named rfid in your PHPMyAdmin. Import the rfid.sql file. If you do not know how to import an SQL file in PHPMyAdmin, simply click on your database, click “Import -> Choose File -> Click rfid.sql -> Open -> Go”

 

If you have done the steps above properly, you should be able to see the logs in http://localhost/rfid/viewlogs.php

That’s it. Enjoy.

 

Hope you like this tutorial. Please share the love by clicking the social media buttons!   

Spread the love
  • 5
    Shares

25 Comments

  • Erick Del Mundo

    Hi how can I send an alert message using javascript instead of digitalWrite(CONN_PIN, HIGH); and digitalWrite(CONN_PIN, LOW); either success or failed? I mean something like this:
    function insertRfIdLog() {
    include ‘connect.php’;
    $cardid = $_POST[‘cardid’];
    $time = time();

    $stmt = $conn->prepare(“INSERT INTO tbllogs(cardid, logdate) VALUES (:card, :dt)”);
    $stmt->bindParam(“:card”, $cardid);
    $stmt->bindParam(“:dt”, $time);
    $stmt->execute();

    //ON THIS PART, this one below is only printing in Serial Monitor
    echo “alert(‘Successfully login’);”;

    }

    • cedcraftscodes

      Hello Erick,

      The log is fetched every x seconds using AJAX.

      $(document).ready(function(){
      function showData()
      {
      $.ajax({

      url: 'log.php',
      type: 'POST',
      data: {action : 'showLogs'},
      dataType: 'html',
      success: function(result)
      {
      $('#logs').html(result);
      },
      error: function()
      {
      alert("Failed to fetch logs!");
      }
      })
      }

      //Fetch rfid logs in database every 2.5 seconds
      setInterval(function(){ showData(); }, 2500);
      });

      You may need to store the size of the current logs. When a new request to fetch the rfids in database is sent to your web server, compare the count of current logs to the new one..
      If you need to have “real-time” events, you may need to use Websockets in Javascript. *you can use Socket.io to publish events.

    • cedcraftscodes

      Hello Erick,

      The log is fetched every x seconds using AJAX.

      $(document).ready(function(){
      function showData()
      {
      $.ajax({

      url: 'log.php',
      type: 'POST',
      data: {action : 'showLogs'},
      dataType: 'html',
      success: function(result)
      {
      $('#logs').html(result);
      },
      error: function()
      {
      alert("Failed to fetch logs!");
      }
      })
      }

      //Fetch rfid logs in database every 2.5 seconds
      setInterval(function(){ showData(); }, 2500);
      });

      You may need to store the size of the current logs. When a new request to fetch the rfids in the database is sent to your web server, compare the count of current logs to the new one..
      If you need to have “real-time” events, you may need to use Websockets in Javascript. *you can use Socket.io to publish events.

  • Erick Del Mundo

    Hi CEDCRAFTSCODES, Thank you very much for the quick reply, I understand that the viewlogs.php refreshes every 2.5 seconds to fetch the data from the mysql database using Jquery Ajax. But is there a way aside of setting “error pin” to high to give an alert message in the browser like alert(‘Unable to login’); I’m looking into websockets now but it will be a great help for me if you can teach me that part 🙂 So far this is what I’ve try but not working for me:

    function insertRfIdLog() {
    include ‘connect.php’;
    $cardid = $_POST[‘cardid’];
    $time = time();

    $stmt = $conn->prepare(“INSERT INTO tbllogs(cardid, logdate) VALUES (:card, :dt)”);
    $stmt->bindParam(“:card”, $cardid);
    $stmt->bindParam(“:dt”, $time);
    $stmt->execute();

    //This part prints only in the Serial Monitor but no output in the browser, I’m trying this as an alternative to Success Pin
    High or Error Pin High:

    if ($stmt) {
    echo “alert(‘Successfully login’);”;
    }
    else {
    echo “alert(‘Successfully login’);”;
    }
    }

    • cedcraftscodes

      Hi Erick,
      For the logic, the NodeMCU device sends an HTTP post request to the server. The server will then return a response, which will then be read by NodeMcu device which in our case, the “success” message. I don’t think that PHP is enough to cater to what you are trying to accomplish. You may want to look into NodeJS and Socket io. The logic would be, your wifi module will send a message to the server. The server will then broadcast a message to your client to display alert / whatever operations you may need.

      https://socket.io/docs/#Sending-and-getting-data-acknowledgements

      Thanks,
      Cedric

      • Erick Del Mundo

        Thanks for info Cedric, I understand now that the NodeMCU only sends POST or GET request to the server. But is there other way to send a message in the browser without websocket and node.js? I’m looking to server.send() that I found here: https://techtutorialsx.com/2016/10/15/esp8266-http-server-serving-html-javascript-and-css/ , I wonder if you could help me to integrate that in your code? Because I’m getting error what I tried this code:

        const char * javascriptCode = ” “

        “ “

        “ “

        “”

        ” alert(\”Hello from the ESP8266!\”); “

        “”

        “ “

        “ “;

        server.on(“/javascript”, []() { //Define the handling function for the javascript path

        server.send(200, “text/html”, javascriptCode);

        });

        Thank you again

        • cedcraftscodes

          Where do you want to see the alert? Upon checking the link, the NodeMCU in the tutorial works as a web server, not an HTTP client. If you are into a web server, I have a tutorial about chat app which will teach you how to set up your own web server (Your NodeMCU will act as a web server). Visit this link. https://devcraze.com/tutorials/internet-of-things/create-awesome-wifi-chat-with-captive-portal-using-nodemcu-esp8266/

          But if you want to post it in a browser using your PHP codes, your best bet was to use “Polling” / sending request every second……

          • Erick Del Mundo

            Thank you Cedric, I really appreciate your quick response and help 🙂 I’ll take a look at your other tutorial, but to explain further this what I’m doing with your tutorial above, I modified it, what I’m trying to do is to register each RFID card to a single unique person every time they swipe their card. So whenever the person try to swipe twice, there will be an alert message of “RFID card exist, unable to register duplicated card”, so in your PHP code that I modified I tried this and also this is the part I want to have an alert message instead of making the led light set to high or low:

            if ($stmt) {
            echo “alert(‘Card was successfully registered!’);”;
            }
            else {
            echo “alert(‘RFID card exist, unable to register duplicated card!’);”;
            }

            BUT what’s happening is those messages are only printing in the serial monitor and not in the browser?

            AND also if I’m going to click the OK button from the alert message the page will automatically refresh without adding this setInterval(function(){ showData(); }, 2500); in viewlogs.php. because I’m using bootstrap modal to enter the username of the person

            Here’s the screenshot of what I’m trying to do: https://imgur.com/0qxKv8d

            Thank you again

          • evanz1234

            Goodmorning ced, I have encountered these errors in your arduino codes.

            :\Users\User\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:84:9: error: ‘WiFiClient’ does not name a type

            WiFiClient & getStream(void) __attribute__ ((deprecated)) ;

            ^

            C:\Users\User\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:85:9: error: ‘WiFiClient’ does not name a type

            WiFiClient * getStreamPtr(void);

            ^

            C:\Users\User\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:97:9: error: ‘WiFiClient’ does not name a type

            WiFiClient * _tcp;

            ^

            C:\Users\User\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:98:9: error: ‘WiFiClientSecure’ does not name a type

            WiFiClientSecure * _tcps;

            ^

            Multiple libraries were found for “MFRC522.h”
            Used: C:\Users\User\Documents\Arduino\libraries\MFRC522
            Not used: C:\Users\User\Documents\Arduino\libraries\arduino_857547
            Not used: C:\Users\User\Documents\Arduino\libraries\MFRC522-1.4.3
            exit status 1
            Error compiling for board NodeMCU 1.0 (ESP-12E Module).

          • cedcraftscodes

            Install the lower version of esp8266 in your board manager.

            Multiple libraries were found for “MFRC522.h”
            Please remove duplicating RFID libraries in your Arduino and re upload the codes again.

  • Erick Del Mundo

    My mistake it was:

    if ($stmt) {
    echo “alert(‘Successfully login’);”;
    }
    else {
    echo “alert(‘Unable login’);”;
    }

  • khabibshahid

    Thanks for tutorial, it’s worked!
    But could you help to advice, if we need change decimal of CardID= Value to HEX?

    • cedcraftscodes

      You can modify the code to output the value to HEX. The if statement help to display leading zero at the beginning.


      String code="";
      for (byte i = 0; i < mfrc522.uid.size; i++){ if (mfrc522.uid.uidByte[i] < 0x10){ code += "0"; } code += String(mfrc522.uid.uidByte[i], HEX); }

    • cedcraftscodes

      I think that error is a false positive. Try to compile and upload the code again. If it doesn’t work, make sure you selected the correct board for your NodeMcu 🙂

      • evanz1234

        I encountered the same error, I tried to compile and upload the code again but it gave me the same error. I also selected the NODE MCU 0.9 ( ESP12- Module) and NODE MCU 1.0 ( ESP12- Module) board but it didn’t work. Same error occured

        • cedcraftscodes

          Hello, please go to “Tools -> Boards -> Board manager”. Search for “Esp8266” and install a lower version, then try to re-upload the codes.

  • intelij

    Great tutorial, I am a newbie just stumbled upon your tutorial. Do you have the same tutorial but using GSM module/sim card to send a text instead? Also may i ask what devices I would need to have a similar setup, I do see the listing under requirements? Is there a standard kit i can purchase to archive this or i have to search for all these from different vendors? Any pointers will be greatly appreciated. Thank you in advance.

  • papi fake

    Hello there, I have a request.

    How do you fetch data from the database whilst scanning a rfid card.

    I mean, I have an idea that involves a vb studio program that fetch a data from a database (I don’t know which you like to recommend whether sql or oracle) while scanning it using a rfid card.

    So if you could. Please help me.

  • rizqi007

    Hi CEDCRAFTSCODES, its a great tutorial, its helpfull to understood abaut connect rfid to php, thanks
    I want to ask you, i have idea to link rfid code with database, so when rfid scan with nodemcu, form on local host call database i have made. what should i do? change arduino program or sql program?

    sorry for my grammar

    • cedcraftscodes

      I would like to clarify what you want to achieve.
      If you want to display their name/time they logged on a screen or LCD 7 segments display you just need to change the return of server into a JSON or XML that contains the information about the RFID. e.g. response {rifid: 1510965, name: “cedcraftscodes”, datetime: “02/13/2019 7:30 AM”}, your Nodemcu module will then parse the response and display it to user.

      If you just want to store those ids in Nodemcu, just make a request to your server/rest API which outputs the RFID codes, store it in NodeMCU Spiffs. When the user scans, fetch data in SPIFFS.

Leave a Reply

Your email address will not be published. Required fields are marked *