@@ -29,32 +29,46 @@ static inline bool TWI_FailedAcknowledge(Twi *pTwi) {
29
29
}
30
30
31
31
static inline bool TWI_WaitTransferComplete (Twi *_twi, uint32_t _timeout) {
32
- while (!TWI_TransferComplete (_twi)) {
33
- if (TWI_FailedAcknowledge (_twi))
32
+ uint32_t _status_reg = 0 ;
33
+ while ((_status_reg & TWI_SR_TXCOMP) != TWI_SR_TXCOMP) {
34
+ _status_reg = TWI_GetStatus (_twi);
35
+
36
+ if (_status_reg & TWI_SR_NACK)
34
37
return false ;
38
+
35
39
if (--_timeout == 0 )
36
40
return false ;
37
41
}
38
42
return true ;
39
43
}
40
44
41
45
static inline bool TWI_WaitByteSent (Twi *_twi, uint32_t _timeout) {
42
- while (!TWI_ByteSent (_twi)) {
43
- if (TWI_FailedAcknowledge (_twi))
46
+ uint32_t _status_reg = 0 ;
47
+ while ((_status_reg & TWI_SR_TXRDY) != TWI_SR_TXRDY) {
48
+ _status_reg = TWI_GetStatus (_twi);
49
+
50
+ if (_status_reg & TWI_SR_NACK)
44
51
return false ;
52
+
45
53
if (--_timeout == 0 )
46
54
return false ;
47
55
}
56
+
48
57
return true ;
49
58
}
50
59
51
60
static inline bool TWI_WaitByteReceived (Twi *_twi, uint32_t _timeout) {
52
- while (!TWI_ByteReceived (_twi)) {
53
- if (TWI_FailedAcknowledge (_twi))
61
+ uint32_t _status_reg = 0 ;
62
+ while ((_status_reg & TWI_SR_RXRDY) != TWI_SR_RXRDY) {
63
+ _status_reg = TWI_GetStatus (_twi);
64
+
65
+ if (_status_reg & TWI_SR_NACK)
54
66
return false ;
67
+
55
68
if (--_timeout == 0 )
56
69
return false ;
57
70
}
71
+
58
72
return true ;
59
73
}
60
74
@@ -175,22 +189,30 @@ void TwoWire::beginTransmission(int address) {
175
189
// devices will behave oddly if they do not see a STOP.
176
190
//
177
191
uint8_t TwoWire::endTransmission (uint8_t sendStop) {
192
+ uint8_t error = 0 ;
178
193
// transmit buffer (blocking)
179
194
TWI_StartWrite (twi, txAddress, 0 , 0 , txBuffer[0 ]);
180
- TWI_WaitByteSent (twi, XMIT_TIMEOUT);
181
- int sent = 1 ;
182
- while (sent < txBufferLength) {
183
- TWI_WriteByte (twi, txBuffer[sent++]);
184
- TWI_WaitByteSent (twi, XMIT_TIMEOUT);
195
+ if (!TWI_WaitByteSent (twi, XMIT_TIMEOUT))
196
+ error = 2 ; // error, got NACK on address transmit
197
+
198
+ if (error == 0 ) {
199
+ uint16_t sent = 1 ;
200
+ while (sent < txBufferLength) {
201
+ TWI_WriteByte (twi, txBuffer[sent++]);
202
+ if (!TWI_WaitByteSent (twi, XMIT_TIMEOUT))
203
+ error = 3 ; // error, got NACK during data transmmit
204
+ }
205
+ }
206
+
207
+ if (error == 0 ) {
208
+ TWI_Stop (twi);
209
+ if (!TWI_WaitTransferComplete (twi, XMIT_TIMEOUT))
210
+ error = 4 ; // error, finishing up
185
211
}
186
- TWI_Stop ( twi);
187
- TWI_WaitTransferComplete (twi, XMIT_TIMEOUT);
188
-
189
- // empty buffer
190
- txBufferLength = 0 ;
191
212
213
+ txBufferLength = 0 ; // empty buffer
192
214
status = MASTER_IDLE;
193
- return sent ;
215
+ return error ;
194
216
}
195
217
196
218
// This provides backwards compatibility with the original
0 commit comments