18
Reading RFID Tags

In this chapter you will

  • Learn how to implement RFID readers with your Arduino
  • See how to save variables in the Arduino EEPROM
  • Design the framework for an Arduino-based RFID access system

Radio-frequency identification (RFID) is a wireless system that uses electromagnetic fields to transfer data from one object to another, without the two objects touching. You can build an Arduino that reads common RFID tags and cards to create access systems and to control digital outputs. You may have used an RFID card before, such as an access card that you use to unlock a door or a public transport card that you hold in front of a reader on the bus. Figure 18-1 shows some examples of RFID tags and cards.

f18001

Figure 18-1: Example RFID devices

Inside RFID Devices

Inside an RFID tag is a tiny integrated circuit with memory that can be accessed by a specialized reader. Most tags don’t have a battery inside; instead, a wire coil antenna in the RFID reader broadcasts a jolt of electromagnetic energy to the tags. They absorb this energy and use it to power their own circuitry, which broadcasts a response back to the RFID reader. Figure 18-2 shows the antenna coil of the RFID reader that we’ll use in this chapter.

f18002

Figure 18-2: Our RFID reader

The card reader we’ll use in this chapter is from PMD Way (part number 113990014). It’s cheap and easy to use, and it operates at 125 kHz; be sure to purchase two or more RFID tags that match that frequency, such as those found at https://pmdway.com/collections/rfid-tags/.

Testing the Hardware

In this section, you’ll connect the RFID reader to the Arduino. Then you’ll test that it’s working with a simple sketch that reads RFID cards and sends the data to the Serial Monitor. To avoid conflict with the serial port between the PC and Arduino, the RFID will be connected to other digital pins and use SoftwareSerial, as we did in Chapter 15 with the GPS receiver module.

The Schematic

Figure 18-3 shows a diagram of the RFID module connections, looking at the top side of the module.

f18003

Figure 18-3: RFID module connections

Testing the Schematic

To make the connections between the RFID reader and the Arduino, follow these steps, using female-to-male jumper wires:

  1. Connect the included coil plug to the antenna pins at the bottom left of the RFID reader board. They are not polarized and can connect either way.
  2. Connect the reader’s GND (pin 2) to Arduino GND.
  3. Connect the reader’s 5 V (pin 1) to Arduino 5 V.
  4. Connect the reader’s RX (pin 4) to Arduino pin D3.
  5. Connect the reader’s TX (pin 5) to Arduino pin D2.

The Test Sketch

Enter and upload Listing 18-1.

// Listing 18-1
#include <SoftwareSerial.h>
SoftwareSerial Serial2(2, 3); 
int data1 = 0;

void setup()
{
  Serial.begin(9600);
  Serial2.begin(9600);
}

void loop() 
{
  if (Serial2.available() > 0) {
    data1 = Serial2.read();
    // display incoming number
    Serial.print(" ");
    Serial.print(data1, DEC);
  }

Listing 18-1: RFID test sketch

Displaying the RFID Tag ID Number

Open the Serial Monitor window and wave an RFID tag over the coil. The results should look similar to Figure 18-4.

f18004

Figure 18-4: Example output from Listing 18-1

Notice that 14 numbers are displayed in the Serial Monitor window. Collectively, these are the RFID tag’s unique ID number, which we’ll use in future sketches to identify the tag being read. Scan all your RFID tags and record their ID numbers, because you’ll need them for the next few projects.

Project #52: Creating a Simple RFID Control System

Now let’s put the RFID system to use. In this project, you’ll learn how to trigger an Arduino event when one of two correct RFID tags is read. The sketch stores two RFID tag numbers; when a card whose ID matches one of those numbers is read by the reader, it will display Accepted in the Serial Monitor. If a card whose ID does not match one of the stored IDs is presented, then the Serial Monitor will display Rejected. We’ll use this as a base to add RFID controls to existing projects.

The Sketch

Enter and upload the following sketch. However, at 1 and 2, replace the x’s in the array with the set of numbers you noted for two of your RFID tags in the previous section. (We discussed arrays in Chapter 6.)

// Project 52 – Creating a Simple RFID Control System
#include <SoftwareSerial.h>
SoftwareSerial Serial2(2, 3);
int data1 = 0;
int ok = -1;
// use Listing 18-1 to find your tags' numbers

1 int tag1[14] = {x, x, x, x, x, x, x, x, x, x, x, x, x, x};
2 int tag2[14] = {x, x, x, x, x, x, x, x, x, x, x, x, x, x};
int newtag[14] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// used for read comparisons

3 boolean comparetag(int aa[14], int bb[14])
{
  boolean ff = false;
  int fg = 0;
  for (int cc = 0 ; cc < 14 ; cc++)
  {
    if (aa[cc] == bb[cc])
    {
      fg++;
    }
  }
  if (fg == 14)
  {
    ff = true;
  }
  return ff;
}
4 void checkmytags() // compares each tag against the tag just read
{
  ok = 0;          // This variable supports decision making.
  // If it is 1, we have a match; 0 is a read but no match,
  // -1 is no read attempt made.
  if (comparetag(newtag, tag1) == true)
  {
5     ok++;
  }
  if (comparetag(newtag, tag2) == true)
  {
6     ok++;
  }
}

void setup()
{
  Serial.begin(9600);
  Serial2.begin(9600);
  Serial2.flush(); // need to flush serial buffer
                   // otherwise first read may not be correct
}

void loop()
{
  ok = -1;
  if (Serial2.available() > 0)     // if a read has been attempted
  {
                // read the incoming number on serial RX
    delay(100); // needed to allow time for the data
                // to come in from the serial buffer
7     for (int z = 0 ; z < 14 ; z++) // read the rest of the tag
    {
      data1 = Serial2.read();
      newtag[z] = data1;
    }
    Serial2.flush(); // stops multiple reads
    // now to match tags up
8     checkmytags();
  }
9   // now do something based on tag type
  if (ok > 0)        // if we had a match
  {
    Serial.println("Accepted");
    ok = -1;
  }
  else if (ok == 0)  // if we didn't have a match
  {
    Serial.println("Rejected");
    ok = -1;
  }
}

Understanding the Sketch

When a tag is presented to the RFID reader, it sends the tag’s numbers, which collectively are its ID number, through the serial port. We capture all 14 of these numbers and place them in the array newtag[] at 7. Next, the tag ID is compared against the two tag ID numbers stored at 1 and 2 using the function checkmytags() at 4 and 8, with the actual comparisons of the tag arrays performed by the function comparetag() at 3.

The comparetag() function accepts the two number arrays as parameters and returns (in Boolean) whether the arrays are identical (true) or different (false). If a match is made, the variable ok is set to 1 at 5 and 6. Finally, at 9, we have the actions to take once the tag read succeeds.

After uploading the sketch, open the Serial Monitor window and present some tags to the reader. The results should be similar to those in Figure 18-5.

f18005

Figure 18-5: Results of Project 52

Storing Data in the Arduino’s Built-in EEPROM

When you define and use a variable in your Arduino sketches, the stored data lasts only until the Arduino is reset or the power is turned off. But what if you want to keep the values for future use, as in the case of the user-changeable secret code for the numeric keypad in Chapter 11? That’s where the EEPROM (electrically erasable read-only memory) comes in. The EEPROM stores variables in memory inside an ATmega328 microcontroller, and the values aren’t lost when the power is turned off.

The EEPROM in the Arduino can store 1,024-byte variables in positions numbered from 0 to 1,023. Recall that a byte can store an integer with a value between 0 and 255, and you begin to see why it’s perfect for storing RFID tag numbers. To use the EEPROM in our sketches, we first call the EEPROM library (included with the Arduino IDE) using the following:

#include <EEPROM.h>

Then, to write a value to the EEPROM, we simply use this:

EEPROM.write(a, b);

Here, a is the position in the EEPROM memory where the information will be stored, and b is the variable holding the information we want to store in the EEPROM at position a.

To retrieve data from the EEPROM, we use this function:

value = EEPROM.read(position); 

This takes the data stored in EEPROM position number position and stores it in the variable value.

Reading and Writing to the EEPROM

Here’s an example of how to read and write to the EEPROM. Enter and upload Listing 18-2.

// Listing 18-2
#include <EEPROM.h>
int zz;

void setup()
{
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop()
{
  Serial.println("Writing random numbers...");
  for (int i = 0; i < 1024; i++) 
  {
    zz = random(255);
1     EEPROM.write(i, zz); 
  }
  Serial.println();
  for (int a = 0; a < 1024; a++)
  {
2     zz = EEPROM.read(a); 
    Serial.print("EEPROM position: ");
    Serial.print(a);
    Serial.print(" contains ");
3     Serial.println(zz); 
    delay(25);
  }
}

Listing 18-2: EEPROM demonstration sketch

In the loop at 1, a random number between 0 and 255 is stored in each EEPROM position. The stored values are retrieved in the second loop at 2, to be displayed in the Serial Monitor at 3.

Once the sketch has been uploaded, open the Serial Monitor. You should see something like Figure 18-6.

f18006

Figure 18-6: Example output from Listing 18-2

Now you’re ready to create a project using the EEPROM.

Project #53: Creating an RFID Control with “Last Action” Memory

Although Project 52 showed how to use RFID to control something, such as a light or electric door lock, we had to assume that nothing would be remembered if the system were reset or the power went out. For example, if a light was on and the power went out, then the light would be off when the power returned. However, you may prefer the Arduino to remember what was happening before the power went out and return to that state. Let’s solve that problem now.

In this project, the last action will be stored in the EEPROM (for example, “locked” or “unlocked”). When the sketch restarts after a power failure or an Arduino reset, the system will revert to the previous state stored in the EEPROM.

The Sketch

Enter and upload the following sketch. As you did for Project 52, replace each x in the arrays at 1 and 2 with the numbers for two of your RFID tags.

// Project 53 – Creating an RFID Control with "Last Action" Memory
#include <SoftwareSerial.h>
SoftwareSerial Serial2(2, 3);
#include <EEPROM.h>
int data1 = 0;
int ok = -1;
int lockStatus = 0;
// use Listing 18-1 to find your tags' numbers
1 int tag1[14] = {
  x, x, x, x, x, x, x, x, x, x, x, x, x, x
};
2 int tag2[14] = {
  x, x, x, x, x, x, x, x, x, x, x, x, x, x
};
int newtag[14] = {
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}; // used for read comparisons

// comparetag compares two arrays and returns true if identical
// this is good for comparing tags
boolean comparetag(int aa[14], int bb[14])
{
  boolean ff = false;
  int fg = 0;
  for (int cc = 0; cc < 14; cc++)
  {
    if (aa[cc] == bb[cc])
    {
      fg++;
    }
  }
  if (fg == 14)
  {
    ff = true;
  }
  return ff;
}
void checkmytags()
// compares each tag against the tag just read
{
  ok = 0;
  if (comparetag(newtag, tag1) == true)
  {
    ok++;
  }
  if (comparetag(newtag, tag2) == true)
  {
    ok++;
  }
}
3 void checkLock()
{
  Serial.print("System Status after restart ");
  lockStatus = EEPROM.read(0);
  if (lockStatus == 1)
  {
    Serial.println("- locked");
    digitalWrite(13, HIGH);
  }
  if (lockStatus == 0)
  {
    Serial.println("- unlocked");
    digitalWrite(13, LOW);
  }
  if ((lockStatus != 1) && (lockStatus != 0))
  {
    Serial.println("EEPROM fault - Replace Arduino hardware");
  }
}
void setup()
{
  Serial.begin(9600);
  Serial2.begin(9600);
  Serial2.flush(); // need to flush serial buffer
  pinMode(13, OUTPUT);
4   checkLock();
}
void loop()
{
  ok = -1;
  if (Serial2.available() > 0)   // if a read has been attempted
  {
    // read the incoming number on serial RX
    delay(100);
    for (int z = 0; z < 14; z++) // read the rest of the tag
    {
      data1 = Serial2.read();
      newtag[z] = data1;
    }
    Serial2.flush();             // prevents multiple reads
    // now to match tags up
    checkmytags();
  }
5   if (ok > 0)                    // if we had a match
  {
    lockStatus = EEPROM.read(0);
    if (lockStatus == 1)         // if locked, unlock it
    {
6       Serial.println("Status - unlocked");
      digitalWrite(13, LOW);
      EEPROM.write(0, 0);
    }
    if (lockStatus == 0)
    {
7       Serial.println("Status - locked");
      digitalWrite(13, HIGH);
      EEPROM.write(0, 1);
    }
    if ((lockStatus != 1) && (lockStatus != 0))
    {
8       Serial.println("EEPROM fault - Replace Arduino hardware");
    }
  }
  else if (ok == 0)              // if we didn't have a match
  {
    Serial.println("Incorrect tag");
    ok = -1;
  }
  delay(500);
}

Understanding the Sketch

This sketch is a modification of Project 52. We use the onboard LED to simulate the status of something that we want to turn on or off every time an acceptable RFID ID tag is read. After a tag has been read and matched, the status of the lock is changed at 5. We store the status of the lock in the first position of the EEPROM. The status is represented by a number: 0 is unlocked and 1 is locked. This status will change (from locked to unlocked and back to locked) after every successful tag read at 6 or 7.

We’ve also introduced a fail-safe in case the EEPROM has worn out. If the value returned from reading the EEPROM is not 0 or 1, we should be notified at 8. Furthermore, the status is checked when the sketch restarts after a reset using the function checkLock() at 1, 2, 3, and 4, which reads the EEPROM value, determines the last status, and then sets the lock to that status (locked or unlocked).

Looking Ahead

Once again, we have used an Arduino board to re-create simply what could be a very complex project. You now have a base to add RFID control to your projects that will allow you to create professional-quality access systems and control digital outputs with the swipe of an RFID card. We’ll demonstrate this again when we revisit RFID in Chapter 20.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.172.252