@@ -413,6 +413,7 @@ MFRC522::StatusCode MFRC522::PCD_CommunicateWithPICC(byte command, ///< The c
413413 byte rxAlign, // /< In: Defines the bit position in backData[0] for the first bit received. Default 0.
414414 bool checkCRC // /< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated.
415415 ) {
416+ const byte software_timeout_ms = 36 ; // 36ms
416417 // Prepare values for BitFramingReg
417418 byte txLastBits = validBits ? *validBits : 0 ;
418419 byte bitFraming = (rxAlign << 4 )+txLastBits; // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
@@ -424,25 +425,29 @@ MFRC522::StatusCode MFRC522::PCD_CommunicateWithPICC(byte command, ///< The c
424425 _driver.PCD_WriteRegister (PCD_Register::BitFramingReg, bitFraming); // Bit adjustments
425426 _driver.PCD_WriteRegister (PCD_Register::CommandReg, command); // Execute the command
426427 if (command == PCD_Command::PCD_Transceive) {
427- PCD_SetRegisterBitMask (PCD_Register::BitFramingReg, 0x80 ); // StartSend=1, transmission of data starts
428+ _driver. PCD_WriteRegister (PCD_Register::BitFramingReg, bitFraming | 0x80 ); // StartSend=1, transmission of data starts
428429 }
429430
430431 // Wait for the command to complete.
431432 // In PCD_Init() we set the TAuto flag in TModeReg. This means the timer automatically starts when the PCD stops transmitting.
432433 // Each iteration of the do-while-loop takes 17.86μs.
433434 // TODO check/modify for other architectures than Arduino Uno 16bit
434- uint16_t i;
435- for (i = 2000 ; i > 0 ; i--) {
435+ long t_delta=0 ;
436+ long t_start=millis ();
437+ while ( (byte)t_delta < software_timeout_ms) {
436438 byte n = _driver.PCD_ReadRegister (PCD_Register::ComIrqReg); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq
437439 if (n & waitIRq) { // One of the interrupts that signal success has been set.
438440 break ;
439441 }
440442 if (n & 0x01 ) { // Timer interrupt - nothing received in 25ms
441- return StatusCode::STATUS_TIMEOUT;
443+ return StatusCode::STATUS_TIMEOUT; // Hardware timeout
442444 }
445+ // todo !! adaptive delay !!
446+ delay (1 ); // prevents bus flood
447+ t_delta = millis () - t_start;
443448 }
444449 // 35.7ms and nothing happened. Communication with the MFRC522 might be down.
445- if (i == 0 ) {
450+ if ((byte)t_delta >= software_timeout_ms ) {
446451 return StatusCode::STATUS_TIMEOUT;
447452 }
448453
0 commit comments