Time tracking with Wemos D1 and RFID

FunduinoLast updated on

An- und Abmeldung per RFID-Tag, Anzeige im Browser

Karte vor das Lesemodul halten, fertig – der Wemos D1 merkt sich, wer sich wann an- oder abgemeldet hat, und zeigt die Übersicht als Webseite im lokalen Netz an.

Das Projekt bringt drei Themen zusammen: RFID zum Erkennen der Tags, die Bibliothek time.h für die Uhrzeit aus dem Internet und einen kleinen Webserver, der die HTML-Seite selbst erzeugt.

Der Sketch ist in vier Abschnitte geteilt, die nacheinander erklärt werden. Wer will, erweitert die Liste der erfassten Personen anschließend selbst.

Browser page with the login status of three employees and a Refresh button
This is what the finished page looks like in the browser.

You need this

RC522 RFID kit - 13.56 MHz, with card and key fob RC522 RFID kit - 13.56 MHz, with card and key fob 2,86 € *Item no. FUN-1010560About the product — RC522 RFID kit - 13.56 MHz, with card and key fob
125 kHz RFID tag - EM4100 chip, credit card size 125 kHz RFID tag - EM4100 chip, credit card size 1,01 € *Item no. F23107076About the product — 125 kHz RFID tag - EM4100 chip, credit card size
RFID tag 13.56 MHz - key fob, passive RFID tag 13.56 MHz - key fob, passive 1,06 € *Item no. F23106945About the product — RFID tag 13.56 MHz - key fob, passive
WeMos D1 Mini ESP8266 - development board with Wi-Fi, 3.3 V WeMos D1 Mini ESP8266 - development board with Wi-Fi, 3.3 V 5,95 € *Item no. F23106678About the product — WeMos D1 Mini ESP8266 - development board with Wi-Fi, 3.3 V

All 4 parts together 10,88 € *

* All prices include statutory VAT, plus shipping costs.

What the project does

Every RFID tag - whether a card or key fob - has its own code. The project assigns names to these codes and records when someone checked in or out.

The Wemos D1 gets the current time from the internet via NTP and serves the overview as a webpage on the local network. It refreshes itself every 60 seconds; there is also a button to reload it immediately.

Browser page with the login status of three employees and a Refresh button
This is what the finished page looks like in the browser.

Install the board

Under File → Preferences, enter an additional Board Manager URL:

https://arduino.esp8266.com/stable/package_esp8266com_index.json

Then install the esp8266 package via the Board Manager. If the board isn’t detected automatically, select it manually via “Select another board and port.”

Input field for additional Board Manager URLs in the settings
File → Settings → Board Manager URL
ESP8266 package in Boards Manager
Install the esp8266 package
1 / 2

Connect the RFID module

The RFID kit consists of the reader module and the tags. Hold a tag in front of it, and the module outputs its code.

In the sketch, SDA on D8 and RST on D3 are specified; the other connections use SPI. The schematic and connection table show the exact pin assignments.

Then install the MFRC522 library.

Pay attention to the tags' frequency: The MFRC522 operates at 13.56 MHz. The card in credit-card format linked in the parts list is a 125 kHz tag and cannot be read with this reader module.

RFID reader module with a card in credit card size and key fob
Reader module and the two tag designs
Pinout of the RFID module
The pins of the RFID module
Wiring the RFID module and Wemos D1 Mini
The circuit diagram
Table of connections between the RFID module and Wemos D1
RFID module connections
MFRC522 Library in the Library Manager
The MFRC522 library
1 / 5

Read the tag codes

Before you can assign names, you need to know which tag has which code. This small program outputs the code of each tag you hold up as a sequence of decimal numbers in the Serial Monitor.

Write down the values – you’ll need them in the main program.

Decimal value of an RFID card in the Serial Monitor
The code read from a tag
Read the code of a tag
#include <MFRC522.h>
// Define RFID connections
#define SDA D8
#define RST D3

// Name the RFID reader
MFRC522 mfrc522(SDA, RST);

// Value read from the RFID card as a sequence of decimal numbers
String WertDEZ;

void setup() 
{
  Serial.begin(9600);
  delay(500);
  SPI.begin();

  // Initialize the RFID reader
  mfrc522.PCD_Init();
}

void loop() 
{
  // Reset the card value
  WertDEZ = "";

  // Start reading when a card is placed on the reader
  if (mfrc522.PICC_IsNewCardPresent()) 
  {
    mfrc522.PICC_ReadCardSerial();

    // Write the card's decimal values to a string
    for (byte i = 0; i < mfrc522.uid.size; i++) 
    {
      WertDEZ = WertDEZ + String(mfrc522.uid.uidByte[i], DEC) + " ";
    }

    // Adjust the wait time when reading multiple values
    delay(1000);

    // Display the decimal value in the Serial Monitor
    Serial.println("decimal value: " + WertDEZ);
  }
}

Variables, time zone, and time server

In the first section of the program, you define where the time comes from and who is being recorded.

A pool of NTP servers - if one fails, the next one takes over automatically. The time zone setting handles the switch between daylight saving time and standard time automatically.

Enter your router’s SSID and password. If you want to record additional people, add them to the MitarbeiterInnen array and adjust the sizes of the AnmeldeStatus and AnmeldeZeit arrays accordingly.

The SSID and password are in plain text in the sketch. So don't share it unchanged.

Global variables and libraries
// Add libraries
#include <ESP8266WebServer.h>
#include <time.h>
#include <MFRC522.h>

// Define RFID connections
#define SDA D8
#define RST D3

// Name the RFID reader
MFRC522 mfrc522(SDA, RST);

char Router[] = "Router_SSID";
char Passwort[] = "xxxxxxxx";

// Value read from the RFID card as a sequence of decimal numbers
String WertDEZ;

/*
  NTP server pool
  # define Zeitserver "de.pool.ntp.org"
  https://www.pool.ntp.org/zone/de
  or, for example, the time server of the Physikalisch-Technische Bundesanstalt
  # define Zeitserver "ptbtime1.ptb.de"
  If a static IP address is used, the entry can also be made directly
  Specify the NTP server as an IP address
  192.53.103.108 -> Physikalisch-Technische Bundesanstalt
*/
#define Zeitserver "de.pool.ntp.org"

/*
  List of time zones
  https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
  Time zone CET = Central European Time -1 -> 1 hour behind
  CEST = Central European Summer Time from
  M3 = March, 5.0 = Sunday in the 5th week, 02 = 2 o'clock
  until M10 = October, 5.0 = Sunday in the 5th week, 03 = 3 o'clock
*/
#define Zeitzone "CET-1CEST,M3.5.0/02,M10.5.0/03"

// time_t contains the number of seconds since 1/1/1970 12 a.m.
time_t aktuelleZeit;

/*
  The tm structure converts the retrieved time into a "readable" format:
  tm_hour -> hour: 0 to 23
  tm_min -> minutes: 0 to 59
  tm_sec -> seconds: 0 to 59
  tm_mday -> day: 1 to 31
  tm_mon -> month: 0 (January) to 11 (December)
  tm_year -> years since 1900
  tm_yday -> days elapsed since January 1 of the year
  tm_isdst -> value > 0 = daylight saving time (dst = daylight saving time)
*/
tm Zeit;

WiFiServer Server(80);
WiFiClient Client;

// Employee names
String MitarbeiterInnen[3] = { "Klaus Drolshagen", "Eva Hilger", "Claudia Kruse" };

// Login status: false = logged out
bool AnmeldeStatus[3] = { false, false, false };

// Login/logout time
String AnmeldeZeit[3];

The setup part

The setup initializes the RFID module, sets the time zone and time server, connects to Wi-Fi, and starts the web server.

Once connected, the serial monitor shows the router name and the Wemos D1's IP address. Enter this address in your browser's address bar.

IP address of the Wemos D1 in the Serial Monitor
The IP address of the Wemos D1
Enter the IP address in the browser’s address bar
Enter the IP address in the browser
1 / 2
The setup part
void setup() 
{
  Serial.begin(9600);
  delay(500);
  SPI.begin();

  // Initialize the RFID receiver
  mfrc522.PCD_Init();

  // Parameters for determining the time
  configTime(Zeitzone, Zeitserver);

  WiFi.begin(Router, Passwort);

  // Establish the connection
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(200);
    Serial.print(".");
  }

  Server.begin();

  // Display the router's SSID
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());

  // Display the D!'s IP
  Serial.println(WiFi.localIP());
}

The loop section with the web server

The loop first reads the current time and then the tag presented. If its code matches one of the stored codes, the corresponding person's attendance status is toggled and the current time is recorded.

The program then builds the HTML page line by line and sends it to the browser: the date with the day of the week, the time, the list of all people with their status and timestamp, and the refresh button.

You need to replace the three example codes in the sketch with the values of your own tags.

There are three errors in the loop to note. First, the minute padding overwrites the already-assembled hour instead of appending to it, so for minutes under ten, only the minute is displayed. Second, the month padding checks the zero-based month but outputs the one-based month, resulting in “010” in October. Third, the Refresh button sends the string WiFi.localIP() instead of the IP address, so it does not work.

Labeled RFID cards with employee portrait photos
Example of card labeling
The loop section with the web server
void loop() 
{
  // Read the current time
  time(&aktuelleZeit);

  // localtime_r -> set the determined time to the local time zone
  localtime_r(&aktuelleZeit, &Zeit);
  
  // Reset the card value
  WertDEZ = "";

  // Start polling when a card is presented
  if (mfrc522.PICC_IsNewCardPresent()) 
  {
    mfrc522.PICC_ReadCardSerial();

    // Write the card's decimal values to a string
    for (byte i = 0; i < mfrc522.uid.size; i++) 
    {
      WertDEZ = WertDEZ + String(mfrc522.uid.uidByte[i], DEC) + " ";
    }

    // Adjust wait time when reading multiple values
    delay(1000);

    // Display the decimal value in the Serial Monitor
    Serial.println("decimal value: " + WertDEZ);
  }

  // Remove trailing spaces
  WertDEZ.trim();

  // Check cards and associate them with employee names and times
  if (WertDEZ.compareTo("195 106 18 23") == 0) 
  {
    AnmeldeStatus[0] = !AnmeldeStatus[0];

    // Reset the login time
    AnmeldeZeit[0] = "";

    // If the hour is < 10 -> prepend a 0
    if (Zeit.tm_hour < 10) AnmeldeZeit[0] = "0";
    AnmeldeZeit[0] = AnmeldeZeit[0] + Zeit.tm_hour + ":";

    // If the minute is < 10 -> prepend a 0
    if (Zeit.tm_min < 10) AnmeldeZeit[0] = "0";
    AnmeldeZeit[0] = AnmeldeZeit[0] + Zeit.tm_min;
  }

  if (WertDEZ.compareTo("227 77 233 22") == 0) 
  {
    AnmeldeStatus[1] = !AnmeldeStatus[1];
    AnmeldeZeit[1] = "";
    if (Zeit.tm_hour < 10) AnmeldeZeit[1] = "0";
    AnmeldeZeit[1] = AnmeldeZeit[1] + Zeit.tm_hour + ":";
    if (Zeit.tm_min < 10) AnmeldeZeit[1] = "0";
    AnmeldeZeit[1] = AnmeldeZeit[1] + Zeit.tm_min;
  }

  if (WertDEZ.compareTo("131 125 21 23") == 0) 
  {
    AnmeldeStatus[2] = !AnmeldeStatus[2];
    AnmeldeZeit[2] = "";

    if (Zeit.tm_hour < 10) AnmeldeZeit[2] = "0";
    AnmeldeZeit[2] = AnmeldeZeit[2] + Zeit.tm_hour + ":";
    if (Zeit.tm_min < 10) AnmeldeZeit[2] = "0";
    AnmeldeZeit[2] = AnmeldeZeit[2] + Zeit.tm_min;
  }

  Client = Server.available();
  if (Client) 
  {
    // Build the page if SeiteAufbauen is true
    boolean SeiteAufbauen = true;

    while (Client.connected()) 
    {
      if (Client.available()) 
      {
        char Zeichen = Client.read();
        if (Zeichen == '\n') 
        {
          // If SeiteAufbauen is true
          if (SeiteAufbauen) 
          {
            // Send the HTTP request
            Client.println("HTTP/1.1 200 OK");
            Client.println("Content-Type: text/html");

            // Blank line is required
            Client.println();

            /*
              Build the HTML page
              the following instructions must be sent using print or println
              println "makes" the source code look nicer
              " must be escaped with \"
            */
            Client.println("<!doctype html>");
            Client.println("<html>");
            Client.println("<body>");

            // Refresh every 60 seconds using a meta tag
            Client.println("<meta http-equiv=\"refresh\" content=\"60\">");
            Client.println("<h1>Employee login status</h1>");
            Client.println("<hr />");

            // Display the current time
            Client.println("<h2>");

            // tm_mday -> display the day of the week
            switch (Zeit.tm_wday) 
            {
              case 0:
                Client.print(F("Sunday"));
                break;
              case 1:
                Client.print(F("Monday"));
                break;
              case 2:
                Client.print(F("Tuesday"));
                break;
              case 3:
                Client.print(F("Wednesday"));
                break;
              case 4:
                Client.print(F("Thursday"));
                break;
              case 5:
                Client.print(F("Friday"));
                break;
              case 6:
                Client.print(F("Saturday"));
                break;
            }
            Client.print(", ");

            // Day: add a leading 0
            if (Zeit.tm_mday < 10) Client.print("0");
            Client.print(Zeit.tm_mday);
            Client.print(".");

            // Month: add a leading 0
            if (Zeit.tm_mon < 10) Client.print("0");
            Client.print(Zeit.tm_mon + 1);
            Client.print(".");

            // tm_year + 1900
            Client.print(Zeit.tm_year + 1900);

            // Time
            Client.print(" Time: ");

            // Hours
            if (Zeit.tm_hour < 10) Client.print("0");
            Client.print(Zeit.tm_hour);
            Client.print(":");

            // Minutes
            if (Zeit.tm_min < 10) Client.print("0");
            Client.print(Zeit.tm_min);
            Client.print(":");

            // Seconds
            if (Zeit.tm_sec < 10) Client.print("0");
            Client.print(Zeit.tm_sec);

            Client.println("</h2>");
            Client.println("<hr />");

            // Display employee names and login status
            for (int i = 0; i < sizeof(MitarbeiterInnen) / sizeof(MitarbeiterInnen[0]); i++) 
            {
              Client.println(MitarbeiterInnen[i]);
              if (AnmeldeStatus[i] == true) Client.println(": logged in since " + AnmeldeZeit[i] + " Uhr");
              else Client.println(": logged out since " + AnmeldeZeit[i] + " Uhr");
              Client.println("<br>");
            }
            Client.println("<hr>");

            Client.println("<form>");

            // Format the refresh button
            Client.print("<input style=\"font-size:16pt; font-weight:bold;");
            Client.print("background-color:#55A96B;");
            Client.print("display:block; cursor:pointer;\"type=\"button\"");
            Client.println(" onClick=\"location.href='WiFi.localIP()'\" value=\"refresh\">");
            Client.println("</form>");
            Client.println("<hr />");

            // Display IPs
            Client.print(F("<b>Own IP: "));
            Client.print(Client.remoteIP());
            Client.print(F("</b>"));
            Client.print(F("<br><b>Client IP (D1): "));
            Client.print(WiFi.localIP());
            Client.print(F("</b>"));
            Client.println("</b>");

            Client.println("</body>");
            Client.print("</html>");

            // HTTP response ends with a newline
            Client.println();

            // Page fully loaded -> exit loop
            break;
          }

          // If a new line (\n) was sent -> build the page
          if (Zeichen == '\n') SeiteAufbauen = true;

          else if (Zeichen != '\r') SeiteAufbauen = false;
          
          delay(1);
          Client.stop();
        }
      }
    }
  }
}
Rate the instructions

Comments

Ask a question or share an experience

Contact us if something doesn’t work. Please include your board and the error message.

We review every comment before publication. Your email address remains with us.