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 (7262 downloads)

 

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

Connection

rfid fritzing

RFID NodeMcu
3.3V 3.3V
RST D2
GND GND
MISO D6
MOSI D7
SCK D5
SDA D4

 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 Pin NodeMcu
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

12 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

  • Erick Del Mundo

    My mistake it was:

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

Leave a Reply

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