1
0
Fork 0

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.
This commit is contained in:
Teo-CD 2024-01-06 00:25:46 +00:00
parent 73ceeb493c
commit 324cf50653
2 changed files with 33 additions and 0 deletions

View file

@ -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

View file

@ -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;
}