1326 lines
58 KiB
C++
1326 lines
58 KiB
C++
/*
|
|
* MFRC522.cpp - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
|
|
* NOTE: Please also check the comments in MFRC522.h - they provide useful hints and background information.
|
|
* Released into the public domain.
|
|
*/
|
|
|
|
#include "mfrc522.hpp"
|
|
|
|
#include <cstring>
|
|
#include <unistd.h>
|
|
|
|
const byte mfrc522::mfrc522_firmware_reference_v0_0[] = {
|
|
0x00, 0x87, 0x98, 0x0f, 0x49, 0xFF, 0x07, 0x19,
|
|
0xBF, 0x22, 0x30, 0x49, 0x59, 0x63, 0xAD, 0xCA,
|
|
0x7F, 0xE3, 0x4E, 0x03, 0x5C, 0x4E, 0x49, 0x50,
|
|
0x47, 0x9A, 0x37, 0x61, 0xE7, 0xE2, 0xC6, 0x2E,
|
|
0x75, 0x5A, 0xED, 0x04, 0x3D, 0x02, 0x4B, 0x78,
|
|
0x32, 0xFF, 0x58, 0x3B, 0x7C, 0xE9, 0x00, 0x94,
|
|
0xB4, 0x4A, 0x59, 0x5B, 0xFD, 0xC9, 0x29, 0xDF,
|
|
0x35, 0x96, 0x98, 0x9E, 0x4F, 0x30, 0x32, 0x8D
|
|
};
|
|
|
|
const byte mfrc522::mfrc522_firmware_reference_v1_0[] = {
|
|
0x00, 0xC6, 0x37, 0xD5, 0x32, 0xB7, 0x57, 0x5C,
|
|
0xC2, 0xD8, 0x7C, 0x4D, 0xD9, 0x70, 0xC7, 0x73,
|
|
0x10, 0xE6, 0xD2, 0xAA, 0x5E, 0xA1, 0x3E, 0x5A,
|
|
0x14, 0xAF, 0x30, 0x61, 0xC9, 0x70, 0xDB, 0x2E,
|
|
0x64, 0x22, 0x72, 0xB5, 0xBD, 0x65, 0xF4, 0xEC,
|
|
0x22, 0xBC, 0xD3, 0x72, 0x35, 0xCD, 0xAA, 0x41,
|
|
0x1F, 0xA7, 0xF3, 0x53, 0x14, 0xDE, 0x7E, 0x02,
|
|
0xD9, 0x0F, 0xB5, 0x5E, 0x25, 0x1D, 0x29, 0x79
|
|
};
|
|
|
|
const byte mfrc522::mfrc522_firmware_reference_v2_0[] = {
|
|
0x00, 0xEB, 0x66, 0xBA, 0x57, 0xBF, 0x23, 0x95,
|
|
0xD0, 0xE3, 0x0D, 0x3D, 0x27, 0x89, 0x5C, 0xDE,
|
|
0x9D, 0x3B, 0xA7, 0x00, 0x21, 0x5B, 0x89, 0x82,
|
|
0x51, 0x3A, 0xEB, 0x02, 0x0C, 0xA5, 0x00, 0x49,
|
|
0x7C, 0x84, 0x4D, 0xB3, 0xCC, 0xD2, 0x1B, 0x81,
|
|
0x5D, 0x48, 0x76, 0xD5, 0x71, 0x61, 0x21, 0xA9,
|
|
0x86, 0x96, 0x83, 0x38, 0xCF, 0x9D, 0x5B, 0x6D,
|
|
0xDC, 0x15, 0xBA, 0x3E, 0x7D, 0x95, 0x3B, 0x2F
|
|
};
|
|
|
|
const byte mfrc522::fm17522_firmware_reference[] = {
|
|
0x00, 0xD6, 0x78, 0x8C, 0xE2, 0xAA, 0x0C, 0x18,
|
|
0x2A, 0xB8, 0x7A, 0x7F, 0xD3, 0x6A, 0xCF, 0x0B,
|
|
0xB1, 0x37, 0x63, 0x4B, 0x69, 0xAE, 0x91, 0xC7,
|
|
0xC3, 0x97, 0xAE, 0x77, 0xF4, 0x37, 0xD7, 0x9B,
|
|
0x7C, 0xF5, 0x3C, 0x11, 0x8F, 0x15, 0xC3, 0xD7,
|
|
0xC1, 0x5B, 0x00, 0x2A, 0xD0, 0x75, 0xDE, 0x9E,
|
|
0x51, 0x64, 0xAB, 0x3E, 0xE9, 0x15, 0xB5, 0xAB,
|
|
0x56, 0x9A, 0x98, 0x82, 0x26, 0xEA, 0x2A, 0x62
|
|
};
|
|
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
// Basic interface functions for communicating with the MFRC522
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
mfrc522::mfrc522(
|
|
unsigned bus, unsigned device, unsigned reset
|
|
) : spi_(bus, device), reset_(reset) {}
|
|
|
|
/**
|
|
* Writes a byte to the specified register in the MFRC522 chip.
|
|
* The interface is described in the datasheet section 8.1.2.
|
|
*/
|
|
void mfrc522::pcd_write_register(
|
|
pcd_register reg, ///< The register to write to. One of the PCD_Register enums.
|
|
byte value ///< The value to write.
|
|
) {
|
|
byte buf[2] = { reg, value };
|
|
spi_.write(buf, 2);
|
|
} // End PCD_WriteRegister()
|
|
|
|
/**
|
|
* Writes a number of bytes to the specified register in the MFRC522 chip.
|
|
* The interface is described in the datasheet section 8.1.2.
|
|
*/
|
|
void mfrc522::pcd_write_register(
|
|
pcd_register reg, ///< The register to write to. One of the PCD_Register enums.
|
|
byte count, ///< The number of bytes to write to the register
|
|
byte *values ///< The values to write. Byte array.
|
|
) {
|
|
byte buf[count + 1] = { reg };
|
|
memcpy(&buf[1], values, count);
|
|
spi_.write(buf, count + 1);
|
|
} // End PCD_WriteRegister()
|
|
|
|
/**
|
|
* Reads a byte from the specified register in the MFRC522 chip.
|
|
* The interface is described in the datasheet section 8.1.2.
|
|
*/
|
|
byte mfrc522::pcd_read_register(
|
|
pcd_register reg ///< The register to read from. One of the PCD_Register enums.
|
|
) {
|
|
auto value = spi_.read_register(reg); // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
|
|
spi_.write(0); // TODO: is this correct?
|
|
return value;
|
|
} // End PCD_ReadRegister()
|
|
|
|
/**
|
|
* Reads a number of bytes from the specified register in the MFRC522 chip.
|
|
* The interface is described in the datasheet section 8.1.2.
|
|
*/
|
|
void mfrc522::pcd_read_register(
|
|
pcd_register reg, ///< The register to read from. One of the PCD_Register enums.
|
|
byte count, ///< The number of bytes to read
|
|
byte *values, ///< Byte array to store the values in.
|
|
byte rx_align ///< Only bit positions rxAlign..7 in values[0] are updated.
|
|
) {
|
|
if (count == 0) {
|
|
return;
|
|
}
|
|
//Serial.print(F("Reading ")); Serial.print(count); printf(" bytes from register."));
|
|
//byte address = reg; // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
|
|
byte index = 1; // Index in values array.
|
|
//count--; // One read is performed outside of the loop
|
|
byte value = spi_.read_register(reg); // Tell MFRC522 which address we want to read
|
|
if (rx_align) { // Only update bit positions rxAlign..7 in values[0]
|
|
// Create bit mask for bit positions rxAlign..7
|
|
byte mask = (0xFF << rx_align) & 0xFF;
|
|
|
|
// Apply mask to both current value of values[0] and the new data in value.
|
|
values[0] = (values[0] & ~mask) | (value & mask);
|
|
}
|
|
else {
|
|
values[0] = value;
|
|
}
|
|
while (index < count) {
|
|
values[index] = spi_.read_register(reg); // Read value and tell that we want to read the same address again.
|
|
index++;
|
|
}
|
|
spi_.write(0); // Read the final byte. Send 0 to stop reading.
|
|
} // End PCD_ReadRegister()
|
|
|
|
/**
|
|
* Sets the bits given in mask in register reg.
|
|
*/
|
|
void mfrc522::pcd_set_register_bit_mask(
|
|
pcd_register reg, ///< The register to update. One of the PCD_Register enums.
|
|
byte mask ///< The bits to set.
|
|
) {
|
|
byte tmp;
|
|
tmp = pcd_read_register(reg);
|
|
pcd_write_register(reg, tmp | mask); // set bit mask
|
|
} // End PCD_SetRegisterBitMask()
|
|
|
|
/**
|
|
* Clears the bits given in mask from register reg.
|
|
*/
|
|
void mfrc522::pcd_clear_register_bit_mask(
|
|
pcd_register reg, ///< The register to update. One of the PCD_Register enums.
|
|
byte mask ///< The bits to clear.
|
|
) {
|
|
byte tmp;
|
|
tmp = pcd_read_register(reg);
|
|
pcd_write_register(reg, tmp & (~mask)); // clear bit mask
|
|
} // End PCD_ClearRegisterBitMask()
|
|
|
|
|
|
/**
|
|
* Use the CRC coprocessor in the MFRC522 to calculate a CRC_A.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::pcd_calculate_crc(
|
|
byte *data, ///< In: Pointer to the data to transfer to the FIFO for CRC calculation.
|
|
byte length, ///< In: The number of bytes to transfer.
|
|
byte *result ///< Out: Pointer to result buffer. Result is written to result[0..1], low byte first.
|
|
) {
|
|
pcd_write_register(CommandReg, PCD_Idle); // Stop any active command.
|
|
pcd_write_register(DivIrqReg, 0x04); // Clear the CRCIRq interrupt request bit
|
|
pcd_write_register(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization
|
|
pcd_write_register(FIFODataReg, length, data); // Write data to the FIFO
|
|
pcd_write_register(CommandReg, PCD_CalcCRC); // Start the calculation
|
|
|
|
// Wait for the CRC calculation to complete. Each iteration of the while-loop takes 17.73μs.
|
|
// TODO check/modify for other architectures than Arduino Uno 16bit
|
|
|
|
// Wait for the CRC calculation to complete. Each iteration of the while-loop takes 17.73us.
|
|
for (uint16_t i = 5000; i > 0; i--) {
|
|
// DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved
|
|
auto n = pcd_read_register(DivIrqReg);
|
|
if (n & 0x04) { // CRCIRq bit set - calculation done
|
|
pcd_write_register(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO.
|
|
// Transfer the result from the registers to the result buffer
|
|
result[0] = pcd_read_register(CRCResultRegL);
|
|
result[1] = pcd_read_register(CRCResultRegH);
|
|
return STATUS_OK;
|
|
}
|
|
}
|
|
// 89ms passed and nothing happend. Communication with the MFRC522 might be down.
|
|
return STATUS_TIMEOUT;
|
|
} // End PCD_CalculateCRC()
|
|
|
|
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
// Functions for manipulating the MFRC522
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
/**
|
|
* Initializes the MFRC522 chip.
|
|
*/
|
|
void mfrc522::pcd_init()
|
|
{
|
|
reset_.set_direction(gpio::output);
|
|
reset_.set_value(gpio::low);
|
|
usleep(50'000);
|
|
reset_.set_value(gpio::high);
|
|
|
|
// Reset baud rates
|
|
pcd_write_register(TxModeReg, 0x00);
|
|
pcd_write_register(RxModeReg, 0x00);
|
|
// Reset ModWidthReg
|
|
pcd_write_register(ModWidthReg, 0x26);
|
|
|
|
// When communicating with a PICC we need a timeout if something goes wrong.
|
|
// f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo].
|
|
// TPrescaler_Hi are the four low bits in TModeReg. TPrescaler_Lo is TPrescalerReg.
|
|
pcd_write_register(TModeReg, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds
|
|
pcd_write_register(TPrescalerReg, 0xA9); // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25μs.
|
|
pcd_write_register(TReloadRegH, 0x03); // Reload timer with 0x3E8 = 1000, ie 25ms before timeout.
|
|
pcd_write_register(TReloadRegL, 0xE8);
|
|
|
|
pcd_write_register(TxASKReg, 0x40); // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting
|
|
pcd_write_register(ModeReg, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (ISO 14443-3 part 6.2.4)
|
|
pcd_antenna_on(); // Enable the antenna driver pins TX1 and TX2 (they were disabled by the reset)
|
|
} // End PCD_Init()
|
|
|
|
|
|
/**
|
|
* Performs a soft reset on the MFRC522 chip and waits for it to be ready again.
|
|
*/
|
|
void mfrc522::pcd_reset()
|
|
{
|
|
pcd_write_register(CommandReg, PCD_SoftReset); // Issue the SoftReset command.
|
|
// The datasheet does not mention how long the SoftRest command takes to complete.
|
|
// But the MFRC522 might have been in soft power-down mode (triggered by bit 4 of CommandReg)
|
|
// Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74μs. Let us be generous: 50ms.
|
|
uint8_t count = 0;
|
|
do {
|
|
// Wait for the PowerDown bit in CommandReg to be cleared (max 3x50ms)
|
|
usleep(50'000);
|
|
} while ((pcd_read_register(CommandReg) & (1 << 4)) && (++count) < 3);
|
|
} // End PCD_Reset()
|
|
|
|
/**
|
|
* Turns the antenna on by enabling pins TX1 and TX2.
|
|
* After a reset these pins are disabled.
|
|
*/
|
|
void mfrc522::pcd_antenna_on()
|
|
{
|
|
auto value = pcd_read_register(TxControlReg);
|
|
if ((value & 0x03) != 0x03) {
|
|
pcd_write_register(TxControlReg, value | 0x03);
|
|
}
|
|
} // End PCD_AntennaOn()
|
|
|
|
/**
|
|
* Turns the antenna off by disabling pins TX1 and TX2.
|
|
*/
|
|
void mfrc522::pcd_antenna_off()
|
|
{
|
|
pcd_clear_register_bit_mask(TxControlReg, 0x03);
|
|
} // End PCD_AntennaOff()
|
|
|
|
/**
|
|
* Get the current MFRC522 Receiver Gain (RxGain[2:0]) value.
|
|
* See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
|
|
* NOTE: Return value scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits.
|
|
*
|
|
* @return Value of the RxGain, scrubbed to the 3 bits used.
|
|
*/
|
|
byte mfrc522::pcd_get_antenna_gain()
|
|
{
|
|
return pcd_read_register(RFCfgReg) & (0x07 << 4);
|
|
} // End PCD_GetAntennaGain()
|
|
|
|
/**
|
|
* Set the MFRC522 Receiver Gain (RxGain) to value specified by given mask.
|
|
* See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
|
|
* NOTE: Given mask is scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits.
|
|
*/
|
|
void mfrc522::pcd_set_antenna_gain(byte mask)
|
|
{
|
|
if (pcd_get_antenna_gain() != mask) { // only bother if there is a change
|
|
pcd_clear_register_bit_mask(RFCfgReg, (0x07 << 4)); // clear needed to allow 000 pattern
|
|
pcd_set_register_bit_mask(RFCfgReg, mask & (0x07 << 4)); // only set RxGain[2:0] bits
|
|
}
|
|
} // End PCD_SetAntennaGain()
|
|
|
|
/**
|
|
* Performs a self-test of the MFRC522
|
|
* See 16.1.1 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
|
|
*
|
|
* @return Whether or not the test passed. Or false if no firmware reference is available.
|
|
*/
|
|
bool mfrc522::pcd_perform_self_test() {
|
|
// This follows directly the steps outlined in 16.1.1
|
|
// 1. Perform a soft reset.
|
|
pcd_reset();
|
|
|
|
// 2. Clear the internal buffer by writing 25 bytes of 00h
|
|
byte zeroes[25] = { 0 };
|
|
pcd_write_register(FIFOLevelReg, 0x80); // flush the FIFO buffer
|
|
pcd_write_register(FIFODataReg, 25, zeroes); // write 25 bytes of 00h to FIFO
|
|
pcd_write_register(CommandReg, PCD_Mem); // transfer to internal buffer
|
|
|
|
// 3. Enable self-test
|
|
pcd_write_register(AutoTestReg, 0x09);
|
|
|
|
// 4. Write 00h to FIFO buffer
|
|
pcd_write_register(FIFODataReg, 0x00);
|
|
|
|
// 5. Start self-test by issuing the CalcCRC command
|
|
pcd_write_register(CommandReg, PCD_CalcCRC);
|
|
|
|
// 6. Wait for self-test to complete
|
|
byte n;
|
|
for (uint8_t i = 0; i < 0xFF; i++) {
|
|
// The datasheet does not specify exact completion condition except
|
|
// that FIFO buffer should contain 64 bytes.
|
|
// While selftest is initiated by CalcCRC command
|
|
// it behaves differently from normal CRC computation,
|
|
// so one can't reliably use DivIrqReg to check for completion.
|
|
// It is reported that some devices does not trigger CRCIRq flag
|
|
// during selftest.
|
|
n = pcd_read_register(FIFOLevelReg);
|
|
if (n >= 64) {
|
|
break;
|
|
}
|
|
}
|
|
pcd_write_register(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO.
|
|
|
|
// 7. Read out resulting 64 bytes from the FIFO buffer.
|
|
byte result[64];
|
|
pcd_read_register(FIFODataReg, 64, result, 0);
|
|
|
|
// Auto self-test done
|
|
// Reset AutoTestReg register to be 0 again. Required for normal operation.
|
|
pcd_write_register(AutoTestReg, 0x00);
|
|
|
|
// Determine firmware version (see section 9.3.4.8 in spec)
|
|
auto version = pcd_read_register(VersionReg);
|
|
|
|
// Pick the appropriate reference values
|
|
const byte *reference;
|
|
switch (version) {
|
|
case 0x88: // Fudan Semiconductor FM17522 clone
|
|
reference = fm17522_firmware_reference;
|
|
break;
|
|
case 0x90: // Version 0.0
|
|
reference = mfrc522_firmware_reference_v0_0;
|
|
break;
|
|
case 0x91: // Version 1.0
|
|
reference = mfrc522_firmware_reference_v1_0;
|
|
break;
|
|
case 0x92: // Version 2.0
|
|
reference = mfrc522_firmware_reference_v2_0;
|
|
break;
|
|
default: // Unknown version
|
|
return false; // abort test
|
|
}
|
|
|
|
// Verify that the results match up to our expectations
|
|
for (uint8_t i = 0; i < 64; i++) {
|
|
// TODO: is this correct?
|
|
if (result[i] != reference[i]) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Test passed; all is good.
|
|
return true;
|
|
} // End PCD_PerformSelfTest()
|
|
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
// Power control
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
//IMPORTANT NOTE!!!!
|
|
//Calling any other function that uses CommandReg will disable soft power down mode !!!
|
|
//For more details about power control, refer to the datasheet - page 33 (8.6)
|
|
|
|
void mfrc522::pcd_soft_power_down() // Note : Only soft power down mode is available throught software
|
|
{
|
|
auto val = pcd_read_register(CommandReg); // Read state of the command register
|
|
val |= (1<<4);// set PowerDown bit ( bit 4 ) to 1
|
|
pcd_write_register(CommandReg, val);//write new value to the command register
|
|
}
|
|
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
// Functions for communicating with PICCs
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
/**
|
|
* Executes the Transceive command.
|
|
* CRC validation can only be done if backData and backLen are specified.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::pcd_transceive_data(
|
|
byte *send_data, ///< Pointer to the data to transfer to the FIFO.
|
|
byte send_len, ///< Number of bytes to transfer to the FIFO.
|
|
byte *back_data, ///< nullptr or pointer to buffer if data should be read back after executing the command.
|
|
byte *back_len, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned.
|
|
byte *valid_bits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. Default nullptr.
|
|
byte rx_align, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0.
|
|
bool check_crc ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated.
|
|
) {
|
|
byte waitIRq = 0x30; // RxIRq and IdleIRq
|
|
return pcd_communicate_with_picc(PCD_Transceive, waitIRq,
|
|
send_data, send_len, back_data, back_len, valid_bits, rx_align, check_crc);
|
|
} // End PCD_TransceiveData()
|
|
|
|
/**
|
|
* Transfers data to the MFRC522 FIFO, executes a command, waits for completion and transfers data back from the FIFO.
|
|
* CRC validation can only be done if backData and backLen are specified.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::pcd_communicate_with_picc(
|
|
byte command, ///< The command to execute. One of the PCD_Command enums.
|
|
byte wait_irq, ///< The bits in the ComIrqReg register that signals successful completion of the command.
|
|
byte *send_data, ///< Pointer to the data to transfer to the FIFO.
|
|
byte send_len, ///< Number of bytes to transfer to the FIFO.
|
|
byte *back_data, ///< nullptr or pointer to buffer if data should be read back after executing the command.
|
|
byte *back_len, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned.
|
|
byte *valid_bits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits.
|
|
byte rx_align, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0.
|
|
bool check_crc ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated.
|
|
) {
|
|
// Prepare values for BitFramingReg
|
|
byte txLastBits = valid_bits ? *valid_bits : 0;
|
|
byte bitFraming = (rx_align << 4) + txLastBits; // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
|
|
|
|
pcd_write_register(CommandReg, PCD_Idle); // Stop any active command.
|
|
pcd_write_register(ComIrqReg, 0x7F); // Clear all seven interrupt request bits
|
|
pcd_write_register(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization
|
|
pcd_write_register(FIFODataReg, send_len, send_data); // Write sendData to the FIFO
|
|
pcd_write_register(BitFramingReg, bitFraming); // Bit adjustments
|
|
pcd_write_register(CommandReg, command); // Execute the command
|
|
if (command == PCD_Transceive) {
|
|
pcd_set_register_bit_mask(BitFramingReg, 0x80); // StartSend=1, transmission of data starts
|
|
}
|
|
|
|
// Wait for the command to complete.
|
|
// In PCD_Init() we set the TAuto flag in TModeReg. This means the timer automatically starts when the PCD stops transmitting.
|
|
// Each iteration of the do-while-loop takes 17.86μs.
|
|
// TODO check/modify for other architectures than Arduino Uno 16bit
|
|
uint16_t i;
|
|
for (i = 2000; i > 0; i--) {
|
|
byte n = pcd_read_register(ComIrqReg); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq
|
|
if (n & wait_irq) { // One of the interrupts that signal success has been set.
|
|
break;
|
|
}
|
|
if (n & 0x01) { // Timer interrupt - nothing received in 25ms
|
|
return STATUS_TIMEOUT;
|
|
}
|
|
}
|
|
// 35.7ms and nothing happend. Communication with the MFRC522 might be down.
|
|
if (i == 0) {
|
|
return STATUS_TIMEOUT;
|
|
}
|
|
|
|
// Stop now if any errors except collisions were detected.
|
|
auto error_reg_value = pcd_read_register(ErrorReg); // ErrorReg[7..0] bits are: WrErr TempErr reserved BufferOvfl CollErr CRCErr ParityErr ProtocolErr
|
|
if (error_reg_value & 0x13) { // BufferOvfl ParityErr ProtocolErr
|
|
return STATUS_ERROR;
|
|
}
|
|
|
|
byte _validBits = 0;
|
|
|
|
// If the caller wants data back, get it from the MFRC522.
|
|
if (back_data && back_len) {
|
|
byte n = pcd_read_register(FIFOLevelReg); // Number of bytes in the FIFO
|
|
if (n > *back_len) {
|
|
return STATUS_NO_ROOM;
|
|
}
|
|
*back_len = n; // Number of bytes returned
|
|
pcd_read_register(FIFODataReg, n, back_data, rx_align); // Get received data from FIFO
|
|
_validBits = pcd_read_register(ControlReg) & 0x07; // RxLastBits[2:0] indicates the number of valid bits in the last received byte. If this value is 000b, the whole byte is valid.
|
|
if (valid_bits) {
|
|
*valid_bits = _validBits;
|
|
}
|
|
}
|
|
|
|
// Tell about collisions
|
|
if (error_reg_value & 0x08) { // CollErr
|
|
return STATUS_COLLISION;
|
|
}
|
|
|
|
// Perform CRC_A validation if requested.
|
|
if (back_data && back_len && check_crc) {
|
|
// In this case a MIFARE Classic NAK is not OK.
|
|
if (*back_len == 1 && _validBits == 4) {
|
|
return STATUS_MIFARE_NACK;
|
|
}
|
|
// We need at least the CRC_A value and all 8 bits of the last byte must be received.
|
|
if (*back_len < 2 || _validBits != 0) {
|
|
return STATUS_CRC_WRONG;
|
|
}
|
|
// Verify CRC_A - do our own calculation and store the control in controlBuffer.
|
|
byte control_buffer[2];
|
|
auto status = pcd_calculate_crc(&back_data[0], *back_len - 2, &control_buffer[0]);
|
|
if (status != STATUS_OK) {
|
|
return status;
|
|
}
|
|
if ((back_data[*back_len - 2] != control_buffer[0]) || (back_data[*back_len - 1] != control_buffer[1])) {
|
|
return STATUS_CRC_WRONG;
|
|
}
|
|
}
|
|
|
|
return STATUS_OK;
|
|
} // End PCD_CommunicateWithPICC()
|
|
|
|
/**
|
|
* Transmits a REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame.
|
|
* Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::picc_request_a(
|
|
byte *buffer_atqa, ///< The buffer to store the ATQA (Answer to request) in
|
|
byte *buffer_size ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
|
|
) {
|
|
return picc_reqa_or_wupa(PICC_CMD_REQA, buffer_atqa, buffer_size);
|
|
} // End PICC_RequestA()
|
|
|
|
/**
|
|
* Transmits a Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and prepare for anticollision or selection. 7 bit frame.
|
|
* Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::picc_wakeup_a(
|
|
byte *buffer_atqa, ///< The buffer to store the ATQA (Answer to request) in
|
|
byte *buffer_size ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
|
|
) {
|
|
return picc_reqa_or_wupa(PICC_CMD_WUPA, buffer_atqa, buffer_size);
|
|
} // End PICC_WakeupA()
|
|
|
|
/**
|
|
* Transmits REQA or WUPA commands.
|
|
* Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::picc_reqa_or_wupa(
|
|
byte command, ///< The command to send - PICC_CMD_REQA or PICC_CMD_WUPA
|
|
byte *buffer_atqa, ///< The buffer to store the ATQA (Answer to request) in
|
|
byte *buffer_size ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
|
|
) {
|
|
|
|
if (buffer_atqa == nullptr || *buffer_size < 2) { // The ATQA response is 2 bytes long.
|
|
return STATUS_NO_ROOM;
|
|
}
|
|
pcd_clear_register_bit_mask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared.
|
|
byte valid_bits = 7; // For REQA and WUPA we need the short frame format - transmit only 7 bits of the last (and only) byte. TxLastBits = BitFramingReg[2..0]
|
|
auto status = pcd_transceive_data(&command, 1, buffer_atqa, buffer_size, &valid_bits);
|
|
if (status != STATUS_OK) {
|
|
return status;
|
|
}
|
|
if (*buffer_size != 2 || valid_bits != 0) { // ATQA must be exactly 16 bits.
|
|
return STATUS_ERROR;
|
|
}
|
|
return STATUS_OK;
|
|
} // End PICC_REQA_or_WUPA()
|
|
|
|
/**
|
|
* Transmits SELECT/ANTICOLLISION commands to select a single PICC.
|
|
* Before calling this function the PICCs must be placed in the READY(*) state by calling PICC_RequestA() or PICC_WakeupA().
|
|
* On success:
|
|
* - The chosen PICC is in state ACTIVE(*) and all other PICCs have returned to state IDLE/HALT. (Figure 7 of the ISO/IEC 14443-3 draft.)
|
|
* - The UID size and value of the chosen PICC is returned in *uid along with the SAK.
|
|
*
|
|
* A PICC UID consists of 4, 7 or 10 bytes.
|
|
* Only 4 bytes can be specified in a SELECT command, so for the longer UIDs two or three iterations are used:
|
|
* UID size Number of UID bytes Cascade levels Example of PICC
|
|
* ======== =================== ============== ===============
|
|
* single 4 1 MIFARE Classic
|
|
* double 7 2 MIFARE Ultralight
|
|
* triple 10 3 Not currently in use?
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::picc_select(
|
|
uid_t *uid, ///< Pointer to Uid struct. Normally output, but can also be used to supply a known UID.
|
|
byte valid_bits ///< The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size.
|
|
) {
|
|
bool use_cascade_tag;
|
|
byte cascade_level = 1;
|
|
status_code result;
|
|
byte count;
|
|
byte uid_index; // The first index in uid->uidByte[] that is used in the current Cascade Level.
|
|
byte buffer[9]; // The SELECT/ANTICOLLISION commands uses a 7 byte standard frame + 2 bytes CRC_A
|
|
byte buffer_used; // The number of bytes used in the buffer, ie the number of bytes to transfer to the FIFO.
|
|
byte tx_last_bits; // Used in BitFramingReg. The number of valid bits in the last transmitted byte.
|
|
byte *response_buffer;
|
|
byte response_length;
|
|
|
|
// Description of buffer structure:
|
|
// Byte 0: SEL Indicates the Cascade Level: PICC_CMD_SEL_CL1, PICC_CMD_SEL_CL2 or PICC_CMD_SEL_CL3
|
|
// Byte 1: NVB Number of Valid Bits (in complete command, not just the UID): High nibble: complete bytes, Low nibble: Extra bits.
|
|
// Byte 2: UID-data or CT See explanation below. CT means Cascade Tag.
|
|
// Byte 3: UID-data
|
|
// Byte 4: UID-data
|
|
// Byte 5: UID-data
|
|
// Byte 6: BCC Block Check Character - XOR of bytes 2-5
|
|
// Byte 7: CRC_A
|
|
// Byte 8: CRC_A
|
|
// The BCC and CRC_A are only transmitted if we know all the UID bits of the current Cascade Level.
|
|
//
|
|
// Description of bytes 2-5: (Section 6.5.4 of the ISO/IEC 14443-3 draft: UID contents and cascade levels)
|
|
// UID size Cascade level Byte2 Byte3 Byte4 Byte5
|
|
// ======== ============= ===== ===== ===== =====
|
|
// 4 bytes 1 uid0 uid1 uid2 uid3
|
|
// 7 bytes 1 CT uid0 uid1 uid2
|
|
// 2 uid3 uid4 uid5 uid6
|
|
// 10 bytes 1 CT uid0 uid1 uid2
|
|
// 2 CT uid3 uid4 uid5
|
|
// 3 uid6 uid7 uid8 uid9
|
|
|
|
// Sanity checks
|
|
if (valid_bits > 80) {
|
|
return STATUS_INVALID;
|
|
}
|
|
|
|
// Prepare MFRC522
|
|
pcd_clear_register_bit_mask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared.
|
|
|
|
// Repeat Cascade Level loop until we have a complete UID.
|
|
auto uid_complete = false;
|
|
while (!uid_complete) {
|
|
// Set the Cascade Level in the SEL byte, find out if we need to use the Cascade Tag in byte 2.
|
|
switch (cascade_level) {
|
|
case 1:
|
|
buffer[0] = PICC_CMD_SEL_CL1;
|
|
uid_index = 0;
|
|
use_cascade_tag = valid_bits && uid->size > 4; // When we know that the UID has more than 4 bytes
|
|
break;
|
|
|
|
case 2:
|
|
buffer[0] = PICC_CMD_SEL_CL2;
|
|
uid_index = 3;
|
|
use_cascade_tag = valid_bits && uid->size > 7; // When we know that the UID has more than 7 bytes
|
|
break;
|
|
|
|
case 3:
|
|
buffer[0] = PICC_CMD_SEL_CL3;
|
|
uid_index = 6;
|
|
use_cascade_tag = false; // Never used in CL3.
|
|
break;
|
|
|
|
default:
|
|
return STATUS_INTERNAL_ERROR;
|
|
}
|
|
|
|
// How many UID bits are known in this Cascade Level?
|
|
int8_t current_level_known_bits = valid_bits - (8 * uid_index);
|
|
if (current_level_known_bits < 0) {
|
|
current_level_known_bits = 0;
|
|
}
|
|
// Copy the known bits from uid->uidByte[] to buffer[]
|
|
byte index = 2; // destination index in buffer[]
|
|
if (use_cascade_tag) {
|
|
buffer[index++] = PICC_CMD_CT;
|
|
}
|
|
byte bytesToCopy = current_level_known_bits / 8 + (current_level_known_bits % 8 ? 1 : 0); // The number of bytes needed to represent the known bits for this level.
|
|
if (bytesToCopy) {
|
|
byte maxBytes = use_cascade_tag ? 3 : 4; // Max 4 bytes in each Cascade Level. Only 3 left if we use the Cascade Tag
|
|
if (bytesToCopy > maxBytes) {
|
|
bytesToCopy = maxBytes;
|
|
}
|
|
for (count = 0; count < bytesToCopy; count++) {
|
|
buffer[index++] = uid->uid_byte[uid_index + count];
|
|
}
|
|
}
|
|
// Now that the data has been copied we need to include the 8 bits in CT in currentLevelKnownBits
|
|
if (use_cascade_tag) {
|
|
current_level_known_bits += 8;
|
|
}
|
|
|
|
// Repeat anti collision loop until we can transmit all UID bits + BCC and receive a SAK - max 32 iterations.
|
|
auto select_done = false;
|
|
while (!select_done) {
|
|
// Find out how many bits and bytes to send and receive.
|
|
if (current_level_known_bits >= 32) { // All UID bits in this Cascade Level are known. This is a SELECT.
|
|
//Serial.print(F("SELECT: currentLevelKnownBits=")); printf(currentLevelKnownBits, DEC);
|
|
buffer[1] = 0x70; // NVB - Number of Valid Bits: Seven whole bytes
|
|
// Calculate BCC - Block Check Character
|
|
buffer[6] = buffer[2] ^ buffer[3] ^ buffer[4] ^ buffer[5];
|
|
// Calculate CRC_A
|
|
result = pcd_calculate_crc(buffer, 7, &buffer[7]);
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
tx_last_bits = 0; // 0 => All 8 bits are valid.
|
|
buffer_used = 9;
|
|
// Store response in the last 3 bytes of buffer (BCC and CRC_A - not needed after tx)
|
|
response_buffer = &buffer[6];
|
|
response_length = 3;
|
|
}
|
|
else { // This is an ANTICOLLISION.
|
|
//Serial.print(F("ANTICOLLISION: currentLevelKnownBits=")); printf(currentLevelKnownBits, DEC);
|
|
tx_last_bits = current_level_known_bits % 8;
|
|
count = current_level_known_bits / 8; // Number of whole bytes in the UID part.
|
|
index = 2 + count; // Number of whole bytes: SEL + NVB + UIDs
|
|
buffer[1] = (index << 4) + tx_last_bits; // NVB - Number of Valid Bits
|
|
buffer_used = index + (tx_last_bits ? 1 : 0);
|
|
// Store response in the unused part of buffer
|
|
response_buffer = &buffer[index];
|
|
response_length = sizeof(buffer) - index;
|
|
}
|
|
|
|
// Set bit adjustments
|
|
auto rx_align = tx_last_bits; // Having a separate variable is overkill. But it makes the next line easier to read.
|
|
pcd_write_register(BitFramingReg, (rx_align << 4) + tx_last_bits); // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
|
|
|
|
// Transmit the buffer and receive the response.
|
|
result = pcd_transceive_data(buffer, buffer_used, response_buffer, &response_length, &tx_last_bits, rx_align);
|
|
if (result == STATUS_COLLISION) { // More than one PICC in the field => collision.
|
|
byte valueOfCollReg = pcd_read_register(CollReg); // CollReg[7..0] bits are: ValuesAfterColl reserved CollPosNotValid CollPos[4:0]
|
|
if (valueOfCollReg & 0x20) { // CollPosNotValid
|
|
return STATUS_COLLISION; // Without a valid collision position we cannot continue
|
|
}
|
|
byte collisionPos = valueOfCollReg & 0x1F; // Values 0-31, 0 means bit 32.
|
|
if (collisionPos == 0) {
|
|
collisionPos = 32;
|
|
}
|
|
if (collisionPos <= current_level_known_bits) { // No progress - should not happen
|
|
return STATUS_INTERNAL_ERROR;
|
|
}
|
|
// Choose the PICC with the bit set.
|
|
count = (collisionPos - 1) % 8; // The bit to modify
|
|
index = 1 + ((collisionPos - 1) / 8) + (count ? 1 : 0); // First byte is index 0.
|
|
buffer[index] |= (1 << count);
|
|
//currentLevelKnownBits = collisionPos; // FIXME not used further, maybe bug
|
|
}
|
|
else if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
else { // STATUS_OK
|
|
if (current_level_known_bits >= 32) { // This was a SELECT.
|
|
select_done = true; // No more anticollision
|
|
// We continue below outside the while.
|
|
}
|
|
else { // This was an ANTICOLLISION.
|
|
// We now have all 32 bits of the UID in this Cascade Level
|
|
current_level_known_bits = 32;
|
|
// Run loop again to do the SELECT.
|
|
}
|
|
}
|
|
} // End of while (!selectDone)
|
|
|
|
// We do not check the CBB - it was constructed by us above.
|
|
|
|
// Copy the found UID bytes from buffer[] to uid->uidByte[]
|
|
index = (buffer[2] == PICC_CMD_CT) ? 3 : 2; // source index in buffer[]
|
|
bytesToCopy = (buffer[2] == PICC_CMD_CT) ? 3 : 4;
|
|
for (count = 0; count < bytesToCopy; count++) {
|
|
uid->uid_byte[uid_index + count] = buffer[index++];
|
|
}
|
|
|
|
// Check response SAK (Select Acknowledge)
|
|
if (response_length != 3 || tx_last_bits != 0) { // SAK must be exactly 24 bits (1 byte + CRC_A).
|
|
return STATUS_ERROR;
|
|
}
|
|
// Verify CRC_A - do our own calculation and store the control in buffer[2..3] - those bytes are not needed anymore.
|
|
result = pcd_calculate_crc(response_buffer, 1, &buffer[2]);
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
if ((buffer[2] != response_buffer[1]) || (buffer[3] != response_buffer[2])) {
|
|
return STATUS_CRC_WRONG;
|
|
}
|
|
if (response_buffer[0] & 0x04) { // Cascade bit set - UID not complete yes
|
|
cascade_level++;
|
|
}
|
|
else {
|
|
uid_complete = true;
|
|
uid->sak = response_buffer[0];
|
|
}
|
|
} // End of while (!uidComplete)
|
|
|
|
// Set correct uid->size
|
|
uid->size = 3 * cascade_level + 1;
|
|
|
|
return STATUS_OK;
|
|
} // End PICC_Select()
|
|
|
|
/**
|
|
* Instructs a PICC in state ACTIVE(*) to go to state HALT.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::picc_halt_a()
|
|
{
|
|
// Build command buffer
|
|
byte buffer[4] = { PICC_CMD_HLTA, 0 };
|
|
|
|
// Calculate CRC_A
|
|
auto result = pcd_calculate_crc(buffer, 2, &buffer[2]);
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
|
|
// Send the command.
|
|
// The standard says:
|
|
// If the PICC responds with any modulation during a period of 1 ms after the end of the frame containing the
|
|
// HLTA command, this response shall be interpreted as 'not acknowledge'.
|
|
// We interpret that this way: Only STATUS_TIMEOUT is a success.
|
|
result = pcd_transceive_data(buffer, sizeof(buffer), nullptr, 0);
|
|
if (result == STATUS_TIMEOUT) {
|
|
return STATUS_OK;
|
|
}
|
|
if (result == STATUS_OK) { // That is ironically NOT ok in this case ;-)
|
|
return STATUS_ERROR;
|
|
}
|
|
return result;
|
|
} // End PICC_HaltA()
|
|
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
// Functions for communicating with MIFARE PICCs
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
/**
|
|
* Executes the MFRC522 MFAuthent command.
|
|
* This command manages MIFARE authentication to enable a secure communication to any MIFARE Mini, MIFARE 1K and MIFARE 4K card.
|
|
* The authentication is described in the MFRC522 datasheet section 10.3.1.9 and http://www.nxp.com/documents/data_sheet/MF1S503x.pdf section 10.1.
|
|
* For use with MIFARE Classic PICCs.
|
|
* The PICC must be selected - ie in state ACTIVE(*) - before calling this function.
|
|
* Remember to call PCD_StopCrypto1() after communicating with the authenticated PICC - otherwise no new communications can start.
|
|
*
|
|
* All keys are set to FFFFFFFFFFFFh at chip delivery.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise. Probably STATUS_TIMEOUT if you supply the wrong key.
|
|
*/
|
|
mfrc522::status_code mfrc522::pcd_authenticate(
|
|
byte command, ///< PICC_CMD_MF_AUTH_KEY_A or PICC_CMD_MF_AUTH_KEY_B
|
|
byte block_addr, ///< The block number. See numbering in the comments in the .h file.
|
|
mifare_key const *key, ///< Pointer to the Crypteo1 key to use (6 bytes)
|
|
uid_t *uid ///< Pointer to Uid struct. The first 4 bytes of the UID is used.
|
|
) {
|
|
byte wait_irq = 0x10; // IdleIRq
|
|
// Build command buffer
|
|
byte send_data[12];
|
|
send_data[0] = command;
|
|
send_data[1] = block_addr;
|
|
for (byte i = 0; i < MF_KEY_SIZE; i++) { // 6 key bytes
|
|
send_data[2 + i] = key->key_byte[i];
|
|
}
|
|
// Use the last uid bytes as specified in http://cache.nxp.com/documents/application_note/AN10927.pdf
|
|
// section 3.2.5 "MIFARE Classic Authentication".
|
|
// The only missed case is the MF1Sxxxx shortcut activation,
|
|
// but it requires cascade tag (CT) byte, that is not part of uid.
|
|
for (byte i = 0; i < 4; i++) { // The last 4 bytes of the UID
|
|
send_data[8 + i] = uid->uid_byte[i + uid->size - 4];
|
|
}
|
|
|
|
// Start the authentication.
|
|
return pcd_communicate_with_picc(PCD_MFAuthent, wait_irq, &send_data[0], sizeof send_data);
|
|
} // End PCD_Authenticate()
|
|
|
|
/**
|
|
* Used to exit the PCD from its authenticated state.
|
|
* Remember to call this function after communicating with an authenticated PICC - otherwise no new communications can start.
|
|
*/
|
|
void mfrc522::pcd_stop_crypto1() {
|
|
// Clear MFCrypto1On bit
|
|
pcd_clear_register_bit_mask(Status2Reg, 0x08); // Status2Reg[7..0] bits are: TempSensClear I2CForceHS reserved reserved MFCrypto1On ModemState[2:0]
|
|
} // End PCD_StopCrypto1()
|
|
|
|
/**
|
|
* Reads 16 bytes (+ 2 bytes CRC_A) from the active PICC.
|
|
*
|
|
* For MIFARE Classic the sector containing the block must be authenticated before calling this function.
|
|
*
|
|
* For MIFARE Ultralight only addresses 00h to 0Fh are decoded.
|
|
* The MF0ICU1 returns a NAK for higher addresses.
|
|
* The MF0ICU1 responds to the READ command by sending 16 bytes starting from the page address defined by the command argument.
|
|
* For example; if blockAddr is 03h then pages 03h, 04h, 05h, 06h are returned.
|
|
* A roll-back is implemented: If blockAddr is 0Eh, then the contents of pages 0Eh, 0Fh, 00h and 01h are returned.
|
|
*
|
|
* The buffer must be at least 18 bytes because a CRC_A is also returned.
|
|
* Checks the CRC_A before returning STATUS_OK.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_read(
|
|
byte block_addr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The first page to return data from.
|
|
byte *buffer, ///< The buffer to store the data in
|
|
byte *buffer_size ///< Buffer size, at least 18 bytes. Also number of bytes returned if STATUS_OK.
|
|
) {
|
|
// Sanity check
|
|
if (buffer == nullptr || *buffer_size < 18) {
|
|
return STATUS_NO_ROOM;
|
|
}
|
|
|
|
// Build command buffer
|
|
buffer[0] = PICC_CMD_MF_READ;
|
|
buffer[1] = block_addr;
|
|
// Calculate CRC_A
|
|
auto result = pcd_calculate_crc(buffer, 2, &buffer[2]);
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
|
|
// Transmit the buffer and receive the response, validate CRC_A.
|
|
return pcd_transceive_data(buffer, 4, buffer, buffer_size, nullptr, 0, true);
|
|
} // End MIFARE_Read()
|
|
|
|
/**
|
|
* Writes 16 bytes to the active PICC.
|
|
*
|
|
* For MIFARE Classic the sector containing the block must be authenticated before calling this function.
|
|
*
|
|
* For MIFARE Ultralight the operation is called "COMPATIBILITY WRITE".
|
|
* Even though 16 bytes are transferred to the Ultralight PICC, only the least significant 4 bytes (bytes 0 to 3)
|
|
* are written to the specified address. It is recommended to set the remaining bytes 04h to 0Fh to all logic 0.
|
|
* *
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_write(
|
|
byte block_addr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The page (2-15) to write to.
|
|
byte *buffer, ///< The 16 bytes to write to the PICC
|
|
byte buffer_size ///< Buffer size, must be at least 16 bytes. Exactly 16 bytes are written.
|
|
) {
|
|
// Sanity check
|
|
if (buffer == nullptr || buffer_size < 16) {
|
|
return STATUS_INVALID;
|
|
}
|
|
|
|
// Mifare Classic protocol requires two communications to perform a write.
|
|
// Step 1: Tell the PICC we want to write to block blockAddr.
|
|
byte cmd_buffer[2] = { PICC_CMD_MF_WRITE, block_addr };
|
|
auto result = pcd_mifare_transceive(cmd_buffer, 2); // Adds CRC_A and checks that the response is MF_ACK.
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
|
|
// Step 2: Transfer the data
|
|
result = pcd_mifare_transceive(buffer, buffer_size); // Adds CRC_A and checks that the response is MF_ACK.
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
|
|
return STATUS_OK;
|
|
} // End MIFARE_Write()
|
|
|
|
/**
|
|
* Writes a 4 byte page to the active MIFARE Ultralight PICC.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_ultralight_write(
|
|
byte page, ///< The page (2-15) to write to.
|
|
byte *buffer, ///< The 4 bytes to write to the PICC
|
|
byte buffer_size ///< Buffer size, must be at least 4 bytes. Exactly 4 bytes are written.
|
|
) {
|
|
// Sanity check
|
|
if (buffer == nullptr || buffer_size < 4) {
|
|
return STATUS_INVALID;
|
|
}
|
|
|
|
// Build commmand buffer
|
|
byte cmd_buffer[6];
|
|
cmd_buffer[0] = PICC_CMD_UL_WRITE;
|
|
cmd_buffer[1] = page;
|
|
memcpy(&cmd_buffer[2], buffer, 4);
|
|
|
|
// Perform the write
|
|
auto result = pcd_mifare_transceive(cmd_buffer, 6); // Adds CRC_A and checks that the response is MF_ACK.
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
return STATUS_OK;
|
|
} // End MIFARE_Ultralight_Write()
|
|
|
|
/**
|
|
* MIFARE Decrement subtracts the delta from the value of the addressed block, and stores the result in a volatile memory.
|
|
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
|
|
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
|
|
* Use MIFARE_Transfer() to store the result in a block.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_decrement(
|
|
byte block_addr, ///< The block (0-0xff) number.
|
|
int32_t delta ///< This number is subtracted from the value of block blockAddr.
|
|
) {
|
|
return mifare_two_step_helper(PICC_CMD_MF_DECREMENT, block_addr, delta);
|
|
} // End MIFARE_Decrement()
|
|
|
|
/**
|
|
* MIFARE Increment adds the delta to the value of the addressed block, and stores the result in a volatile memory.
|
|
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
|
|
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
|
|
* Use MIFARE_Transfer() to store the result in a block.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_increment(
|
|
byte block_addr, ///< The block (0-0xff) number.
|
|
int32_t delta ///< This number is added to the value of block blockAddr.
|
|
) {
|
|
return mifare_two_step_helper(PICC_CMD_MF_INCREMENT, block_addr, delta);
|
|
} // End MIFARE_Increment()
|
|
|
|
/**
|
|
* MIFARE Restore copies the value of the addressed block into a volatile memory.
|
|
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
|
|
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
|
|
* Use MIFARE_Transfer() to store the result in a block.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_restore(
|
|
byte block_addr ///< The block (0-0xff) number.
|
|
) {
|
|
// The datasheet describes Restore as a two step operation, but does not explain what data to transfer in step 2.
|
|
// Doing only a single step does not work, so I chose to transfer 0L in step two.
|
|
return mifare_two_step_helper(PICC_CMD_MF_RESTORE, block_addr, 0L);
|
|
} // End MIFARE_Restore()
|
|
|
|
/**
|
|
* Helper function for the two-step MIFARE Classic protocol operations Decrement, Increment and Restore.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_two_step_helper(
|
|
byte command, ///< The command to use
|
|
byte block_addr, ///< The block (0-0xff) number.
|
|
int32_t data ///< The data to transfer in step 2
|
|
) {
|
|
// Step 1: Tell the PICC the command and block address
|
|
byte cmd_buffer[2] = {
|
|
command, block_addr
|
|
}; // We only need room for 2 bytes.
|
|
|
|
auto result = pcd_mifare_transceive(cmd_buffer, 2); // Adds CRC_A and checks that the response is MF_ACK.
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
|
|
// Step 2: Transfer the data
|
|
result = pcd_mifare_transceive(reinterpret_cast<byte*>(&data), 4, true); // Adds CRC_A and accept timeout as success.
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
|
|
return STATUS_OK;
|
|
} // End MIFARE_TwoStepHelper()
|
|
|
|
/**
|
|
* MIFARE Transfer writes the value stored in the volatile memory into one MIFARE Classic block.
|
|
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
|
|
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_transfer(
|
|
byte block_addr ///< The block (0-0xff) number.
|
|
) {
|
|
// Tell the PICC we want to transfer the result into block blockAddr.
|
|
byte cmd_buffer[2] = {
|
|
PICC_CMD_MF_TRANSFER, block_addr
|
|
}; // We only need room for 2 bytes.
|
|
|
|
auto result = pcd_mifare_transceive(cmd_buffer, 2); // Adds CRC_A and checks that the response is MF_ACK.
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
return STATUS_OK;
|
|
} // End MIFARE_Transfer()
|
|
|
|
/**
|
|
* Helper routine to read the current value from a Value Block.
|
|
*
|
|
* Only for MIFARE Classic and only for blocks in "value block" mode, that
|
|
* is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing
|
|
* the block must be authenticated before calling this function.
|
|
*
|
|
* @param[in] block_addr The block (0x00-0xff) number.
|
|
* @param[out] value Current value of the Value Block.
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_get_value(byte block_addr, int32_t *value)
|
|
{
|
|
byte buffer[18];
|
|
byte size = sizeof(buffer);
|
|
|
|
// Read the block
|
|
auto status = mifare_read(block_addr, buffer, &size);
|
|
if (status == STATUS_OK) {
|
|
// Extract the value
|
|
*value = (int32_t(buffer[3]) << 24) | (int32_t(buffer[2]) << 16) | (int32_t(buffer[1]) << 8) | int32_t(buffer[0]);
|
|
}
|
|
return status;
|
|
} // End MIFARE_GetValue()
|
|
|
|
/**
|
|
* Helper routine to write a specific value into a Value Block.
|
|
*
|
|
* Only for MIFARE Classic and only for blocks in "value block" mode, that
|
|
* is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing
|
|
* the block must be authenticated before calling this function.
|
|
*
|
|
* @param[in] block_addr The block (0x00-0xff) number.
|
|
* @param[in] value New value of the Value Block.
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::mifare_set_value(byte block_addr, int32_t value)
|
|
{
|
|
byte buffer[18];
|
|
|
|
// Translate the int32_t into 4 bytes; repeated 2x in value block
|
|
buffer[0] = buffer[8] = (value & 0xFF);
|
|
buffer[1] = buffer[9] = (value & 0xFF00) >> 8;
|
|
buffer[2] = buffer[10] = (value & 0xFF0000) >> 16;
|
|
buffer[3] = buffer[11] = (value & 0xFF000000) >> 24;
|
|
// Inverse 4 bytes also found in value block
|
|
buffer[4] = ~buffer[0];
|
|
buffer[5] = ~buffer[1];
|
|
buffer[6] = ~buffer[2];
|
|
buffer[7] = ~buffer[3];
|
|
// Address 2x with inverse address 2x
|
|
buffer[12] = buffer[14] = block_addr;
|
|
buffer[13] = buffer[15] = ~block_addr;
|
|
|
|
// Write the whole data block
|
|
return mifare_write(block_addr, buffer, 16);
|
|
} // End MIFARE_SetValue()
|
|
|
|
/**
|
|
* Authenticate with a NTAG216.
|
|
*
|
|
* Only for NTAG216. First implemented by Gargantuanman.
|
|
*
|
|
* @param[in] password password.
|
|
* @param[in] p_ack result success???.
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::pcd_ntag216_auth(byte* password, byte p_ack[]) //Authenticate with 32bit password
|
|
{
|
|
// TODO: Fix cmdBuffer length and rxlength. They really should match.
|
|
// (Better still, rxlength should not even be necessary.)
|
|
|
|
byte cmd_buffer[18]; // We need room for 16 bytes data and 2 bytes CRC_A.
|
|
|
|
cmd_buffer[0] = 0x1B; //Comando de autentificacion
|
|
|
|
for (byte i = 0; i < 4; i++)
|
|
cmd_buffer[i + 1] = password[i];
|
|
|
|
auto result = pcd_calculate_crc(cmd_buffer, 5, &cmd_buffer[5]);
|
|
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
|
|
// Transceive the data, store the reply in cmdBuffer[]
|
|
byte wait_irq = 0x30; // RxIRq and IdleIRq
|
|
// byte cmdBufferSize = sizeof(cmdBuffer);
|
|
byte validBits = 0;
|
|
byte rxlength = 5;
|
|
result = pcd_communicate_with_picc(PCD_Transceive, wait_irq,
|
|
cmd_buffer, 7, cmd_buffer, &rxlength, &validBits);
|
|
|
|
p_ack[0] = cmd_buffer[0];
|
|
p_ack[1] = cmd_buffer[1];
|
|
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
|
|
return STATUS_OK;
|
|
} // End PCD_NTAG216_AUTH()
|
|
|
|
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
// Support functions
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
/**
|
|
* Wrapper for MIFARE protocol communication.
|
|
* Adds CRC_A, executes the Transceive command and checks that the response is MF_ACK or a timeout.
|
|
*
|
|
* @return STATUS_OK on success, STATUS_??? otherwise.
|
|
*/
|
|
mfrc522::status_code mfrc522::pcd_mifare_transceive(
|
|
byte *send_data, ///< Pointer to the data to transfer to the FIFO. Do NOT include the CRC_A.
|
|
byte send_len, ///< Number of bytes in sendData.
|
|
bool accept_timeout ///< True => A timeout is also success
|
|
) {
|
|
byte cmd_buffer[18]; // We need room for 16 bytes data and 2 bytes CRC_A.
|
|
|
|
// Sanity check
|
|
if (send_data == nullptr || send_len > 16) {
|
|
return STATUS_INVALID;
|
|
}
|
|
|
|
// Copy sendData[] to cmdBuffer[] and add CRC_A
|
|
memcpy(cmd_buffer, send_data, send_len);
|
|
auto result = pcd_calculate_crc(cmd_buffer, send_len, &cmd_buffer[send_len]);
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
send_len += 2;
|
|
|
|
// Transceive the data, store the reply in cmdBuffer[]
|
|
byte wait_irq = 0x30; // RxIRq and IdleIRq
|
|
byte cmd_buffer_size = sizeof(cmd_buffer);
|
|
byte valid_bits = 0;
|
|
result = pcd_communicate_with_picc(PCD_Transceive, wait_irq, cmd_buffer,
|
|
send_len, cmd_buffer, &cmd_buffer_size, &valid_bits);
|
|
if (accept_timeout && result == STATUS_TIMEOUT) {
|
|
return STATUS_OK;
|
|
}
|
|
if (result != STATUS_OK) {
|
|
return result;
|
|
}
|
|
// The PICC must reply with a 4 bit ACK
|
|
if (cmd_buffer_size != 1 || valid_bits != 4) {
|
|
return STATUS_ERROR;
|
|
}
|
|
if (cmd_buffer[0] != MF_ACK) {
|
|
return STATUS_MIFARE_NACK;
|
|
}
|
|
return STATUS_OK;
|
|
} // End PCD_MIFARE_Transceive()
|
|
|
|
/**
|
|
* Translates the SAK (Select Acknowledge) to a PICC type.
|
|
*
|
|
* @return PICC_Type
|
|
*/
|
|
mfrc522::picc_type mfrc522::picc_get_type(
|
|
byte sak ///< The SAK byte returned from PICC_Select().
|
|
) {
|
|
// http://www.nxp.com/documents/application_note/AN10833.pdf
|
|
// 3.2 Coding of Select Acknowledge (SAK)
|
|
// ignore 8-bit (iso14443 starts with LSBit = bit 1)
|
|
// fixes wrong type for manufacturer Infineon (http://nfc-tools.org/index.php?title=ISO14443A)
|
|
sak &= 0x7F;
|
|
switch (sak) {
|
|
case 0x04:
|
|
return PICC_TYPE_NOT_COMPLETE; // UID not complete
|
|
case 0x09:
|
|
return PICC_TYPE_MIFARE_MINI;
|
|
case 0x08:
|
|
return PICC_TYPE_MIFARE_1K;
|
|
case 0x18:
|
|
return PICC_TYPE_MIFARE_4K;
|
|
case 0x00:
|
|
return PICC_TYPE_MIFARE_UL;
|
|
case 0x10:
|
|
case 0x11:
|
|
return PICC_TYPE_MIFARE_PLUS;
|
|
case 0x01:
|
|
return PICC_TYPE_TNP3XXX;
|
|
case 0x20:
|
|
return PICC_TYPE_ISO_14443_4;
|
|
case 0x40:
|
|
return PICC_TYPE_ISO_18092;
|
|
default:
|
|
return PICC_TYPE_UNKNOWN;
|
|
}
|
|
} // End PICC_GetType()
|
|
|
|
/**
|
|
* Calculates the bit pattern needed for the specified access bits. In the [C1 C2 C3] tuples C1 is MSB (=4) and C3 is LSB (=1).
|
|
*/
|
|
void mfrc522::mifare_set_access_bits(
|
|
byte *access_bit_buffer, ///< Pointer to byte 6, 7 and 8 in the sector trailer. Bytes [0..2] will be set.
|
|
byte g0, ///< Access bits [C1 C2 C3] for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39)
|
|
byte g1, ///< Access bits C1 C2 C3] for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39)
|
|
byte g2, ///< Access bits C1 C2 C3] for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39)
|
|
byte g3 ///< Access bits C1 C2 C3] for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39)
|
|
) {
|
|
byte c1 = ((g3 & 4) << 1) | ((g2 & 4) << 0) | ((g1 & 4) >> 1) | ((g0 & 4) >> 2);
|
|
byte c2 = ((g3 & 2) << 2) | ((g2 & 2) << 1) | ((g1 & 2) << 0) | ((g0 & 2) >> 1);
|
|
byte c3 = ((g3 & 1) << 3) | ((g2 & 1) << 2) | ((g1 & 1) << 1) | ((g0 & 1) << 0);
|
|
|
|
access_bit_buffer[0] = (~c2 & 0xF) << 4 | (~c1 & 0xF);
|
|
access_bit_buffer[1] = c1 << 4 | (~c3 & 0xF);
|
|
access_bit_buffer[2] = c3 << 4 | c2;
|
|
} // End MIFARE_SetAccessBits()
|
|
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
// Convenience functions - does not add extra functionality
|
|
/////////////////////////////////////////////////////////////////////////////////////
|
|
|
|
/**
|
|
* Returns true if a PICC responds to PICC_CMD_REQA.
|
|
* Only "new" cards in state IDLE are invited. Sleeping cards in state HALT are ignored.
|
|
*
|
|
* @return bool
|
|
*/
|
|
bool mfrc522::picc_is_new_card_present() {
|
|
byte buffer_atqa[2];
|
|
byte buffer_size = sizeof buffer_atqa;
|
|
|
|
// Reset baud rates
|
|
pcd_write_register(TxModeReg, 0x00);
|
|
pcd_write_register(RxModeReg, 0x00);
|
|
// Reset ModWidthReg
|
|
pcd_write_register(ModWidthReg, 0x26);
|
|
|
|
auto result = picc_request_a(buffer_atqa, &buffer_size);
|
|
return result == STATUS_OK || result == STATUS_COLLISION;
|
|
} // End PICC_IsNewCardPresent()
|
|
|
|
/**
|
|
* Simple wrapper around PICC_Select.
|
|
* Returns true if a UID could be read.
|
|
* Remember to call PICC_IsNewCardPresent(), PICC_RequestA() or PICC_WakeupA() first.
|
|
* The read UID is available in the class variable uid.
|
|
*
|
|
* @return bool
|
|
*/
|
|
bool mfrc522::picc_read_card_serial() {
|
|
return picc_select(&uid) == STATUS_OK;
|
|
} // End
|