Arque Technologies STEM Robotics Series

RFIDSmart Wallet

Turn the RC522 and its cards into a prepaid wallet. The name and balance live on the card itself: top up, pay and rename it by typing in the Serial Monitor.

You’ll use
  • Arduino UNO
  • RC522 reader/writer
  • Its card and key fob
Try the walletType a command, then tap a card
RC522 white cardRiya key fobnew school IDsecret key
Card memory, sector 1 (tap a card)
Serial Monitor9600 baud · Newline

How RFID works

RFID (radio-frequency identification) is what’s inside metro cards, office passes and library tags. The RC522 is both a reader and a writer: it can also store data on the card.

The reader's radio field powers the card, the card sends its ID, and with the right key the reader can read and write its memory Reader (RC522) Card (no battery) 1 The reader’s radio wavepowers the card’s chip. 2 The card answers withits ID number (UID). 3 With the right key, the readercan read and write its memory.
The card has no battery. Its coil picks up energy from the reader’s 13.56 MHz radio field, which is why it only works within a few centimetres.

Where the wallet lives on the card

The white card and the key fob are MIFARE Classic 1K: 1024 bytes of memory in 16 sectors. Each sector is locked with a key; new cards use the factory key FF FF FF FF FF FF. This project uses sector 1:

MIFARE Classic 1K: 16 sectors × 4 blocks × 16 bytes = 1024 bytesSector 0 · block 0 holds the maker’s data and UID (read only)Block 452697961000000000000000000000000“Riya” as letters (R = 0x52)Block 54151FA00000003000000000000000000“AQ” marker · balance 250 · taps 3Block 600000000000000000000000000000000not usedBlock 7FFFFFFFFFFFFFF078069FFFFFFFFFFFFKey A · access bits · Key B: NEVER writeSector 1Sectors 2–15 · 42 more data blocks free for your own ideas
The balance is stored as 4 bytes with the smallest first: 250 = FA 00 00 00. The two “AQ” bytes mark the card as a wallet, so the code can tell set-up cards from new ones.

Never write to block 7The last block of every sector holds its keys and access bits. Writing the wrong bytes there can lock that sector forever. The code only ever writes blocks 4 and 5.

What you’ll learn

  • How an RFID reader talks to a card with no battery.
  • SPI: the four-wire way the UNO talks to the RC522.
  • How card memory is organised into sectors, blocks and bytes.
  • Unlocking with a key, writing data, and reading it back to check.
  • Reading typed commands from the Serial Monitor.
1

What you need

PartJob
Arduino UNO (FT232) + USB A-to-B cableRuns the code, powers the reader, and shows the Serial Monitor
RC522 RFID reader/writer moduleReads and writes the cards
White card and blue key fob (packed with the RC522)The wallets
7 male-to-female jumper wiresConnect the RC522’s pins to the UNO. Not part of the two items, but needed to join them

Solder the header firstMost RC522 modules come with a loose 8-pin header strip. It must be soldered on (ask a teacher or adult) so the wires make good contact. Just pushing the pins through the holes gives unreliable readings.

2

Wire it up

Unplug the USB cable while wiring. No breadboard is needed: each wire goes straight from the RC522 to the UNO.

RC52213.56 MHzArduinoUNOSDAD10SCKD13MOSID11MISOD12IRQnot connectedGNDGNDRSTD93.3V3.3V3.3V goes to the UNO’s 3.3V pin, never to 5V7 male-to-female jumper wires, straight from module to board
RC522 pinUNO pinWhat it does
SDA (SS)D10Selects the reader
SCKD13SPI clock
MOSID11Data from the UNO to the reader
MISOD12Data from the reader to the UNO
IRQnot connectedNot needed
GNDGNDGround
RSTD9Reset
3.3V3.3VPower: 3.3 V only

3.3V, not 5VThe RC522 is a 3.3-volt module. Connecting its 3.3V pin to the UNO’s 5V pin can damage it. The UNO’s 3.3V pin is next to the 5V pin, so double-check.

Why the UNO’s “L” light flickersD13 is shared by the on-board LED and the SPI clock, so the light blinks whenever the reader is busy. That’s normal.

3

Upload the code

  1. Install the Arduino IDEThen plug in the UNO. If no port appears, install the FTDI driver.
  2. Install the MFRC522 libraryOpen the Library Manager, search for MFRC522 and install it.
  3. UploadChoose Tools → Board → Arduino Uno and your Port, paste the sketch, then click Verify and Upload.
rfid_smart_wallet.ino
// RFID SMART WALLET: Arduino UNO + RC522 reader/writer
// Stores a name and a balance on the card itself.
// Serial Monitor: 9600 baud, line ending "Newline".
// Commands: name Riya | add 100 | pay 30 | clear | cancel | help
#include <SPI.h>
#include <MFRC522.h>

const int SS_PIN = 10, RST_PIN = 9;
const byte NAME_BLOCK = 4;    // sector 1, block 4: the owner's name
const byte MONEY_BLOCK = 5;   // sector 1, block 5: balance and tap count
// Block 7 holds sector 1's keys: never write to it.
const long MAX_BALANCE = 100000;

MFRC522 rfid(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;

String pending = "";          // command waiting for a card tap
long amount = 0;
String newName = "";

void printHelp() {
  Serial.println(F("Commands (then tap a card):"));
  Serial.println(F("  name Riya   set the owner's name"));
  Serial.println(F("  add 100     top up the balance"));
  Serial.println(F("  pay 30      spend from the balance"));
  Serial.println(F("  clear       wipe the wallet"));
  Serial.println(F("  cancel      forget the last command"));
  Serial.println(F("Or just tap a card to see what's on it."));
}

void readCommand() {
  if (!Serial.available()) return;
  String line = Serial.readStringUntil('\n');
  line.trim();
  if (line.length() == 0) return;

  String cmd = line, arg = "";
  int space = line.indexOf(' ');
  if (space > 0) {
    cmd = line.substring(0, space);
    arg = line.substring(space + 1);
    arg.trim();
  }
  cmd.toLowerCase();

  if (cmd == "add" || cmd == "pay") {
    long n = arg.toInt();
    if (n <= 0 || n > MAX_BALANCE) { Serial.println(F("Type an amount, like: add 50")); return; }
    pending = cmd; amount = n;
  } else if (cmd == "name") {
    if (arg.length() == 0) { Serial.println(F("Type a name, like: name Riya")); return; }
    pending = "name"; newName = arg.substring(0, 15);   // 16 bytes incl. end
  } else if (cmd == "clear") {
    pending = "clear";
  } else if (cmd == "cancel") {
    pending = ""; Serial.println(F("Cancelled.")); return;
  } else {
    printHelp(); return;
  }
  Serial.print(F("OK: ")); Serial.print(line); Serial.println(F("  -> now tap a card"));
}

void printUID() {
  Serial.print(F("Card UID:"));
  for (byte i = 0; i < rfid.uid.size; i++) {
    Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(rfid.uid.uidByte[i], HEX);
  }
  Serial.println();
}

bool readBlock(byte block, byte *data) {    // data must hold 18 bytes
  byte size = 18;
  return rfid.MIFARE_Read(block, data, &size) == MFRC522::STATUS_OK;
}

bool writeBlock(byte block, byte *data) {   // writes 16 bytes
  return rfid.MIFARE_Write(block, data, 16) == MFRC522::STATUS_OK;
}

void finish() {
  rfid.PICC_HaltA();
  rfid.PCD_StopCrypto1();
  pending = "";
  Serial.println();
}

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;  // factory key FF FF FF FF FF FF
  Serial.println(F("RFID Smart Wallet ready."));
  printHelp();
}

void loop() {
  readCommand();
  if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial()) return;

  printUID();
  MFRC522::PICC_Type type = rfid.PICC_GetType(rfid.uid.sak);
  if (type != MFRC522::PICC_TYPE_MIFARE_1K && type != MFRC522::PICC_TYPE_MIFARE_4K &&
      type != MFRC522::PICC_TYPE_MIFARE_MINI) {
    Serial.println(F("This card can't store wallet data (not MIFARE Classic)."));
    finish(); return;
  }

  // Unlock sector 1 with key A
  if (rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, NAME_BLOCK, &key, &(rfid.uid)) != MFRC522::STATUS_OK) {
    Serial.println(F("Locked: this card doesn't use the factory key."));
    finish(); return;
  }

  byte nameData[18], money[18];
  if (!readBlock(NAME_BLOCK, nameData) || !readBlock(MONEY_BLOCK, money)) {
    Serial.println(F("Read failed: hold the card still and try again."));
    finish(); return;
  }
  nameData[16] = 0;                                      // make sure the name text ends

  bool ready = (money[0] == 'A' && money[1] == 'Q');   // our wallet marker
  long balance = 0;
  unsigned int taps = 0;
  if (ready) {
    memcpy(&balance, money + 2, 4);
    memcpy(&taps, money + 6, 2);
  }

  if (!ready && pending != "name" && pending != "clear") {
    Serial.println(F("New card. Type: name YourName  then tap it to set it up."));
    finish(); return;
  }

  bool change = true;
  if (pending == "name") {
    memset(nameData, 0, 16);
    newName.getBytes(nameData, 16);
    if (!ready) { balance = 0; taps = 0; }
    Serial.print(F("Name set to ")); Serial.println(newName);
  } else if (pending == "add") {
    if (balance + amount > MAX_BALANCE) { Serial.println(F("Too much: limit is 100000.")); finish(); return; }
    balance += amount;
    Serial.print(F("Added Rs ")); Serial.println(amount);
  } else if (pending == "pay") {
    if (amount > balance) { Serial.println(F("Not enough money on this card.")); change = false; }
    else { balance -= amount; Serial.print(F("Paid Rs ")); Serial.println(amount); }
  } else if (pending == "clear") {
    memset(nameData, 0, 16);
    memset(money, 0, 16);
    if (writeBlock(NAME_BLOCK, nameData) && writeBlock(MONEY_BLOCK, money)) Serial.println(F("Wallet cleared."));
    else Serial.println(F("Write failed: try again."));
    finish(); return;
  } else {
    taps++;                        // just looking: count the tap
  }

  if (change) {
    memset(money, 0, 16);
    money[0] = 'A'; money[1] = 'Q';
    memcpy(money + 2, &balance, 4);
    memcpy(money + 6, &taps, 2);
    bool ok = writeBlock(NAME_BLOCK, nameData) && writeBlock(MONEY_BLOCK, money);
    byte check[18];
    ok = ok && readBlock(MONEY_BLOCK, check) && memcmp(check, money, 16) == 0;  // read back to verify
    if (!ok) { Serial.println(F("Write failed: hold the card still and try again.")); finish(); return; }
  }

  Serial.print(F("Name:    ")); Serial.println(nameData[0] ? (char *)nameData : "(none)");
  Serial.print(F("Balance: Rs ")); Serial.println(balance);
  Serial.print(F("Taps:    ")); Serial.println(taps);
  finish();
}

Tested before publishingThis sketch was compiled for the Arduino UNO with the official AVR core and the MFRC522 library. It uses under half the UNO’s memory.

4

Use your wallet

  1. Open the Serial MonitorSet it to 9600 baud and Newline (both are menus in the Serial Monitor).
  2. Set up a cardType name Riya and press Enter, then hold the white card flat on the reader for a second.
  3. Top upType add 200 and tap the card. The balance is now written on the card.
  4. PayType pay 50 and tap. Try pay 500 to see “Not enough money”.
  5. Prove it’s on the cardUnplug the UNO, plug it back in and tap the card. The name and balance are still there, because they’re stored on the card, not in the Arduino.
Type thisThen tap a card to…
name RiyaSet the owner’s name (up to 15 letters). Also sets up a new card.
add 100Add Rs 100 to the balance (limit 100000).
pay 30Take Rs 30 off, but only if there’s enough.
clearWipe the name and balance.
cancelForget the last command.
(nothing)Just show the card’s name, balance and number of taps.

A learning project, not real moneyMIFARE Classic cards use old security that can be copied, so this shows how stored-value cards work rather than being safe for real payments. Only use your own cards. Bank and metro cards use secret keys, and the reader will report them as “Locked”.

Take it further

  • Class attendance: give each student a card with their name; every tap adds to their “Taps” count.
  • Reward points: rename “Rs” to “points” and use add for good work.
  • Use another block: store a second number in block 6, the spare block in sector 1.
  • Count totals: keep a running total of all payments in a variable and print it after each tap.

Troubleshooting

Nothing happens when I tap a card
  • Check every wire, especially SDA on D10 and RST on D9.
  • 3.3V must go to the UNO’s 3.3V pin and GND to GND.
  • Hold the card flat and still, 1–3 cm from the reader, for about a second.
  • Make sure the header pins are soldered.
Typing a command does nothing

Set the Serial Monitor to 9600 baud and choose Newline in the line-ending menu. Type help to check the UNO is listening.

“Read failed” or “Write failed”

The card moved away mid-write. Hold it still on the reader and tap again. The code reads the data back after every write, so a failed write is always reported.

“Locked: this card doesn’t use the factory key”

That card has its own secret key, like most bank, metro and school cards. Use the white card or key fob that came with the RC522.

“This card can’t store wallet data”

It isn’t a MIFARE Classic card. Some stickers and phone tags use a different type the code doesn’t handle.

No port appears in the IDE

Try another USB cable (some only charge) and install the FTDI driver from the link in step 3.