Make XPLAINBridge serial bridge much more reliable for the reception of characters...
[pub/USBasp.git] / LUFA / Drivers / Peripheral / TWI.c
1 /*
2 Copyright (C) Dean Camera, 2010.
3
4 dean [at] fourwalledcubicle [dot] com
5 www.fourwalledcubicle.com
6 */
7
8 #include "TWI.h"
9
10 bool TWI_StartTransmission(uint8_t SlaveAddress, uint8_t TimeoutMS)
11 {
12 for (;;)
13 {
14 bool BusCaptured = false;
15 uint16_t TimeoutRemaining;
16
17 TWCR = ((1 << TWINT) | (1 << TWSTA) | (1 << TWEN));
18
19 TimeoutRemaining = (TimeoutMS * 100);
20 while (TimeoutRemaining-- && !(BusCaptured))
21 {
22 if (TWCR & (1 << TWINT))
23 {
24 switch (TWSR & TW_STATUS_MASK)
25 {
26 case TW_START:
27 case TW_REP_START:
28 BusCaptured = true;
29 break;
30 case TW_MT_ARB_LOST:
31 TWCR = ((1 << TWINT) | (1 << TWSTA) | (1 << TWEN));
32 continue;
33 default:
34 TWCR = (1 << TWEN);
35 return false;
36 }
37 }
38
39 _delay_us(10);
40 }
41
42 if (!(BusCaptured))
43 {
44 TWCR = (1 << TWEN);
45 return false;
46 }
47
48 TWDR = SlaveAddress;
49 TWCR = ((1 << TWINT) | (1 << TWEN));
50
51 TimeoutRemaining = (TimeoutMS * 100);
52 while (TimeoutRemaining--)
53 {
54 if (TWCR & (1 << TWINT))
55 break;
56
57 _delay_us(10);
58 }
59
60 if (!(TimeoutRemaining))
61 return false;
62
63 switch (TWSR & TW_STATUS_MASK)
64 {
65 case TW_MT_SLA_ACK:
66 case TW_MR_SLA_ACK:
67 return true;
68 default:
69 TWCR = ((1 << TWINT) | (1 << TWSTO) | (1 << TWEN));
70 return false;
71 }
72 }
73 }