2424
2525unsigned char twi_dcount = 18 ;
2626static unsigned char twi_sda , twi_scl ;
27+ static uint32_t twi_clockStretchLimit ;
2728
2829#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)
2930#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;
3738#endif
3839
3940#if F_CPU == FCPU80
40- #define TWI_CLOCK_STRETCH 800
41+ #define TWI_CLOCK_STRETCH_MULTIPLIER 3
4142#else
42- #define TWI_CLOCK_STRETCH 1600
43+ #define TWI_CLOCK_STRETCH_MULTIPLIER 6
4344#endif
4445
4546void twi_setClock (unsigned int freq ){
@@ -60,14 +61,20 @@ void twi_setClock(unsigned int freq){
6061#endif
6162}
6263
64+ void twi_setClockStretchLimit (uint32_t limit ){
65+ twi_clockStretchLimit = limit * TWI_CLOCK_STRETCH_MULTIPLIER ;
66+ }
67+
6368void twi_init (unsigned char sda , unsigned char scl ){
6469 twi_sda = sda ;
6570 twi_scl = scl ;
6671 pinMode (twi_sda , INPUT_PULLUP );
6772 pinMode (twi_scl , INPUT_PULLUP );
6873 twi_setClock (100000 );
74+ twi_setClockStretchLimit (230 ); // default value is 230 uS
6975}
7076
77+
7178void twi_stop (void ){
7279 pinMode (twi_sda , INPUT );
7380 pinMode (twi_scl , INPUT );
@@ -93,12 +100,12 @@ static bool twi_write_start(void) {
93100}
94101
95102static bool twi_write_stop (void ){
96- unsigned int i = 0 ;
103+ uint32_t i = 0 ;
97104 SCL_LOW ();
98105 SDA_LOW ();
99106 twi_delay (twi_dcount );
100107 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
102109 twi_delay (twi_dcount );
103110 SDA_HIGH ();
104111 twi_delay (twi_dcount );
@@ -107,24 +114,24 @@ static bool twi_write_stop(void){
107114}
108115
109116static bool twi_write_bit (bool bit ) {
110- unsigned int i = 0 ;
117+ uint32_t i = 0 ;
111118 SCL_LOW ();
112119 if (bit ) SDA_HIGH ();
113120 else SDA_LOW ();
114121 twi_delay (twi_dcount + 1 );
115122 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
117124 twi_delay (twi_dcount );
118125 return true;
119126}
120127
121128static bool twi_read_bit (void ) {
122- unsigned int i = 0 ;
129+ uint32_t i = 0 ;
123130 SCL_LOW ();
124131 SDA_HIGH ();
125132 twi_delay (twi_dcount + 2 );
126133 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
128135 bool bit = SDA_READ ();
129136 twi_delay (twi_dcount );
130137 return bit ;
0 commit comments