2 Copyright (C) Dean Camera, 2011.
4 dean [at] fourwalledcubicle [dot] com
10 uint8_t TWI_StartTransmission(const uint8_t SlaveAddress
,
11 const uint8_t TimeoutMS
)
15 bool BusCaptured
= false;
16 uint16_t TimeoutRemaining
;
18 TWCR
= ((1 << TWINT
) | (1 << TWSTA
) | (1 << TWEN
));
20 TimeoutRemaining
= (TimeoutMS
* 100);
21 while (TimeoutRemaining
-- && !(BusCaptured
))
23 if (TWCR
& (1 << TWINT
))
25 switch (TWSR
& TW_STATUS_MASK
)
32 TWCR
= ((1 << TWINT
) | (1 << TWSTA
) | (1 << TWEN
));
36 return TWI_ERROR_BusFault
;
43 if (!(TimeoutRemaining
))
46 return TWI_ERROR_BusCaptureTimeout
;
50 TWCR
= ((1 << TWINT
) | (1 << TWEN
));
52 TimeoutRemaining
= (TimeoutMS
* 100);
53 while (TimeoutRemaining
--)
55 if (TWCR
& (1 << TWINT
))
61 if (!(TimeoutRemaining
))
62 return TWI_ERROR_SlaveResponseTimeout
;
64 switch (TWSR
& TW_STATUS_MASK
)
68 return TWI_ERROR_NoError
;
70 TWCR
= ((1 << TWINT
) | (1 << TWSTO
) | (1 << TWEN
));
71 return TWI_ERROR_SlaveNotReady
;
76 uint8_t TWI_ReadPacket(const uint8_t SlaveAddress
,
77 const uint8_t TimeoutMS
,
78 const uint8_t* InternalAddress
,
79 uint8_t InternalAddressLen
,
85 if ((ErrorCode
= TWI_WritePacket(SlaveAddress
, TimeoutMS
, InternalAddress
, InternalAddressLen
,
86 NULL
, 0)) != TWI_ERROR_NoError
)
91 if ((ErrorCode
= TWI_StartTransmission((SlaveAddress
& TWI_DEVICE_ADDRESS_MASK
) | TWI_ADDRESS_READ
,
92 TimeoutMS
)) == TWI_ERROR_NoError
)
96 if (!(TWI_ReceiveByte(Buffer
++, (Length
== 0))))
98 ErrorCode
= TWI_ERROR_SlaveNAK
;
103 TWI_StopTransmission();
109 uint8_t TWI_WritePacket(const uint8_t SlaveAddress
,
110 const uint8_t TimeoutMS
,
111 const uint8_t* InternalAddress
,
112 uint8_t InternalAddressLen
,
113 const uint8_t* Buffer
,
118 if ((ErrorCode
= TWI_StartTransmission((SlaveAddress
& TWI_DEVICE_ADDRESS_MASK
) | TWI_ADDRESS_WRITE
,
119 TimeoutMS
)) == TWI_ERROR_NoError
)
121 while (InternalAddressLen
--)
123 if (!(TWI_SendByte(*(InternalAddress
++))))
125 ErrorCode
= TWI_ERROR_SlaveNAK
;
132 if (!(TWI_SendByte(*(Buffer
++))))
134 ErrorCode
= TWI_ERROR_SlaveNAK
;
139 TWI_StopTransmission();