24
24
25
25
unsigned char twi_dcount = 18 ;
26
26
static unsigned char twi_sda , twi_scl ;
27
+ static uint32_t twi_clockStretchLimit ;
27
28
28
29
#define SDA_LOW () (GPES = (1 << twi_sda)) //Enable SDA (becomes output and since GPO is 0 for the pin, it will pull the line low)
29
30
#define SDA_HIGH () (GPEC = (1 << twi_sda)) //Disable SDA (becomes input and since it has pullup it will go high)
@@ -37,9 +38,9 @@ static unsigned char twi_sda, twi_scl;
37
38
#endif
38
39
39
40
#if F_CPU == FCPU80
40
- #define TWI_CLOCK_STRETCH 800
41
+ #define TWI_CLOCK_STRETCH_MULTIPLIER 3
41
42
#else
42
- #define TWI_CLOCK_STRETCH 1600
43
+ #define TWI_CLOCK_STRETCH_MULTIPLIER 6
43
44
#endif
44
45
45
46
void twi_setClock (unsigned int freq ){
@@ -60,14 +61,20 @@ void twi_setClock(unsigned int freq){
60
61
#endif
61
62
}
62
63
64
+ void twi_setClockStretchLimit (uint32_t limit ){
65
+ twi_clockStretchLimit = limit * TWI_CLOCK_STRETCH_MULTIPLIER ;
66
+ }
67
+
63
68
void twi_init (unsigned char sda , unsigned char scl ){
64
69
twi_sda = sda ;
65
70
twi_scl = scl ;
66
71
pinMode (twi_sda , INPUT_PULLUP );
67
72
pinMode (twi_scl , INPUT_PULLUP );
68
73
twi_setClock (100000 );
74
+ twi_setClockStretchLimit (230 ); // default value is 230 uS
69
75
}
70
76
77
+
71
78
void twi_stop (void ){
72
79
pinMode (twi_sda , INPUT );
73
80
pinMode (twi_scl , INPUT );
@@ -93,12 +100,12 @@ static bool twi_write_start(void) {
93
100
}
94
101
95
102
static bool twi_write_stop (void ){
96
- unsigned int i = 0 ;
103
+ uint32_t i = 0 ;
97
104
SCL_LOW ();
98
105
SDA_LOW ();
99
106
twi_delay (twi_dcount );
100
107
SCL_HIGH ();
101
- while (SCL_READ () == 0 && (i ++ ) < TWI_CLOCK_STRETCH ); // Clock stretching (up to 100us)
108
+ while (SCL_READ () == 0 && (i ++ ) < twi_clockStretchLimit ); // Clock stretching
102
109
twi_delay (twi_dcount );
103
110
SDA_HIGH ();
104
111
twi_delay (twi_dcount );
@@ -107,24 +114,24 @@ static bool twi_write_stop(void){
107
114
}
108
115
109
116
static bool twi_write_bit (bool bit ) {
110
- unsigned int i = 0 ;
117
+ uint32_t i = 0 ;
111
118
SCL_LOW ();
112
119
if (bit ) SDA_HIGH ();
113
120
else SDA_LOW ();
114
121
twi_delay (twi_dcount + 1 );
115
122
SCL_HIGH ();
116
- while (SCL_READ () == 0 && (i ++ ) < TWI_CLOCK_STRETCH );// Clock stretching (up to 100us)
123
+ while (SCL_READ () == 0 && (i ++ ) < twi_clockStretchLimit );// Clock stretching
117
124
twi_delay (twi_dcount );
118
125
return true;
119
126
}
120
127
121
128
static bool twi_read_bit (void ) {
122
- unsigned int i = 0 ;
129
+ uint32_t i = 0 ;
123
130
SCL_LOW ();
124
131
SDA_HIGH ();
125
132
twi_delay (twi_dcount + 2 );
126
133
SCL_HIGH ();
127
- while (SCL_READ () == 0 && (i ++ ) < TWI_CLOCK_STRETCH );// Clock stretching (up to 100us)
134
+ while (SCL_READ () == 0 && (i ++ ) < twi_clockStretchLimit );// Clock stretching
128
135
bool bit = SDA_READ ();
129
136
twi_delay (twi_dcount );
130
137
return bit ;
0 commit comments