- uint16_t TimeoutRemaining;
-
- twi->MASTER.ADDR = SlaveAddress;
-
- TimeoutRemaining = (TimeoutMS * 100);
- while (TimeoutRemaining)
- {
- uint8_t status = twi->MASTER.STATUS;
- if (bitmask_is_set(status, TWI_MASTER_WIF_bm | TWI_MASTER_ARBLOST_bm))
- {
- // Case 1: Arbitration lost. Try again. (or error)
- twi->MASTER.ADDR = SlaveAddress;
- }
- else if (bitmask_is_set(status, TWI_MASTER_WIF_bm | TWI_MASTER_RXACK_bm))
- {
- // Case 2: No response from slave.
- // We need to release the bus.
- TWI_StopTransmission(twi);
- return TWI_ERROR_SlaveResponseTimeout;
- }
- else if (status & TWI_MASTER_WIF_bm)
- {
- // Case 3: Slave ACK the Write. Ready!
- return TWI_ERROR_NoError;
- }
- else if (status & TWI_MASTER_RIF_bm)
- {
- // Case 4: Slave ACK the Read. Ready! (a byte will be read)
- return TWI_ERROR_NoError;
- }
- // Still waiting..
- _delay_us(10);
- TimeoutRemaining--;
- }
-
- if (!(TimeoutRemaining)) {
- if (twi->MASTER.STATUS & TWI_MASTER_CLKHOLD_bm) {
- // Release the bus if we're holding it.
- TWI_StopTransmission(twi);
- }
- }
- return TWI_ERROR_BusCaptureTimeout;
+ uint16_t TimeoutRemaining;
+
+ TWI->MASTER.ADDR = SlaveAddress;
+
+ TimeoutRemaining = (TimeoutMS * 100);
+ while (TimeoutRemaining)
+ {
+ uint8_t status = TWI->MASTER.STATUS;
+
+ if ((status & (TWI_MASTER_WIF_bm | TWI_MASTER_ARBLOST_bm)) == (TWI_MASTER_WIF_bm | TWI_MASTER_ARBLOST_bm))
+ {
+ TWI->MASTER.ADDR = SlaveAddress;
+ }
+ else if ((status & (TWI_MASTER_WIF_bm | TWI_MASTER_RXACK_bm)) == (TWI_MASTER_WIF_bm | TWI_MASTER_RXACK_bm))
+ {
+ TWI_StopTransmission(twi);
+ return TWI_ERROR_SlaveResponseTimeout;
+ }
+ else if (status & (TWI_MASTER_WIF_bm | TWI_MASTER_RIF_bm))
+ {
+ return TWI_ERROR_NoError;
+ }
+
+ _delay_us(10);
+ TimeoutRemaining--;
+ }
+
+ if (!(TimeoutRemaining)) {
+ if (TWI->MASTER.STATUS & TWI_MASTER_CLKHOLD_bm) {
+ TWI_StopTransmission(twi);
+ }
+ }
+
+ return TWI_ERROR_BusCaptureTimeout;