From 324cf50653e2d37715f277d0a5dcec9630ed27a1 Mon Sep 17 00:00:00 2001 From: Teo-CD Date: Sat, 6 Jan 2024 00:25:46 +0000 Subject: [PATCH] RFID: Implement writing to blocks In order to set the ID to the tag, we need to be able to write blocks. Implement writeBlock() similarly to readBlock() to allow that. Make sure to clean the communication buffer and handle failure states, this will become more important for dual RFID readers as will allow 'chaining' calls and cover both readers without keeping track of what reader sees what tag. Only allow to write a byte for now, we don't need more. --- include/RFID.h | 10 ++++++++++ src/RFID.cpp | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/include/RFID.h b/include/RFID.h index c134fa4..168eca4 100644 --- a/include/RFID.h +++ b/include/RFID.h @@ -98,6 +98,16 @@ private: * @return True if read succeeded, false otherwise. */ bool readBlock(MFRC522Constants::Uid &tagUid, byte blockAddr); + + /** + * Write data to tagUid at blockAddr and return if the write succeeded or not. + * The tag needs to be already woken up. + * @param tagUid Uid of the tag to write to. + * @param blockAddr Address of the block to write to. + * @param data Byte to write. + * @return True if write succeeded, false otherwise. + */ + bool writeBlock(MFRC522Constants::Uid &tagUid, byte blockAddr, uint8_t data); }; #endif //JIN_BARBAPAPA_RFID_H diff --git a/src/RFID.cpp b/src/RFID.cpp index fd40870..7df626d 100644 --- a/src/RFID.cpp +++ b/src/RFID.cpp @@ -116,3 +116,26 @@ bool RFID::readBlock(MFRC522Constants::Uid &uidToRead, byte blockAddr) { mfrc.PICC_HaltA(); return status == MFRC522Constants::STATUS_OK; } + +bool RFID::writeBlock(MFRC522Constants::Uid &uidToRead, byte blockAddr, uint8_t data) { + if (mfrc.PCD_Authenticate( + MFRC522Constants::PICC_Command::PICC_CMD_MF_AUTH_KEY_A, + blockAddr, (&defaultKey),&uidToRead)!= MFRC522Constants::STATUS_OK) { + Serial.println("writeBlock: Failed to authenticate"); + mfrc.PICC_HaltA(); + return false; + } + + byte size = sizeof(comData); + for (byte& bufferByte: comData) + bufferByte = 0; + + *comData = data; + + MFRC522::StatusCode status = mfrc.MIFARE_Write(blockAddr, comData, size); + // Needed otherwise no new communications can happen. + mfrc.PCD_StopCrypto1(); + // No need to keep the tag active. + mfrc.PICC_HaltA(); + return status == MFRC522Constants::STATUS_OK; +}