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