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