1111#include <compat/twi.h>
1212
1313#include "SerialDebug.h"
14- #include "Timer.h"
15-
16- static volatile long _sec ;
14+ #include "Millis.h"
1715
1816/*
1917 i2c_io - write and read bytes to a slave I2C device
@@ -241,11 +239,6 @@ uint8_t i2c_io(uint8_t device_addr, const uint8_t *ap, uint16_t an,
241239 return (status );
242240}
243241
244- static void incSec ()
245- {
246- ++ _sec ;
247- }
248-
249242/*
250243 i2c_init - Initialize the I2C port
251244 */
@@ -254,10 +247,7 @@ void i2c_init(uint8_t bdiv)
254247 TWSR = 0 ; // Set prescalar for 1
255248 TWBR = bdiv ; // Set bit rate register
256249
257- // init timer 2
258- _sec = 0 ;
259- // Timer1Init(1000);
260- // Timer1SetCallback(incSec);
250+ MillisInit ();
261251}
262252
263253static volatile uint8_t _i2cIsRunning ;
@@ -314,13 +304,35 @@ uint8_t I2CSendnRecvData(uint8_t address, const uint8_t * txdata,
314304 */
315305uint8_t I2CCheckAlive (uint8_t address )
316306{
307+ if (_i2cIsRunning )
308+ return 1 ;
309+ _i2cIsRunning = 1 ;
310+
317311 uint8_t status ;
318312 uint8_t retVal = 0 ;
313+ unsigned long long initMillis = 0 ;
314+ uint8_t isValid = 0 ;
319315
320316 // send I2C start
321317 TRACE ()
322318 TWCR = (1 << TWINT ) | (1 << TWEN ) | (1 << TWSTA ); // Send start condition
323- while (!(TWCR & (1 << TWINT ))) ; // Wait for TWINT to be set
319+
320+ initMillis = Millis ();
321+ isValid = 0 ;
322+ while ( Millis () - initMillis < 100 )
323+ {
324+ if ((TWCR & (1 << TWINT ))) // Wait for TWINT to be set in 100ms
325+ {
326+ isValid = 1 ;
327+ break ;
328+ }
329+ }
330+ if (!isValid )
331+ {
332+ retVal = 4 ;
333+ goto _I2CCheckAlive_sendstop ;
334+ }
335+
324336 TRACE ()
325337 status = TWSR & 0xf8 ;
326338 if (status != 0x08 ) // Check that START was sent OK
@@ -334,7 +346,22 @@ uint8_t I2CCheckAlive(uint8_t address)
334346 {
335347 TWDR = (address << 1 ) & 0xfe ; // Load device address and R/W = 0;
336348 TWCR = (1 << TWINT ) | (1 << TWEN ); // Start transmission
337- while (!(TWCR & (1 << TWINT ))); // Wait for TWINT to be set
349+
350+ initMillis = Millis ();
351+ isValid = 0 ;
352+ while ( Millis () - initMillis < 100 )
353+ {
354+ if ((TWCR & (1 << TWINT ))) // Wait for TWINT to be set in 100ms
355+ {
356+ isValid = 1 ;
357+ break ;
358+ }
359+ }
360+ if (!isValid )
361+ {
362+ retVal = 4 ;
363+ goto _I2CCheckAlive_sendstop ;
364+ }
338365
339366 TRACE ()
340367 status = TWSR & 0xf8 ;
@@ -346,14 +373,16 @@ uint8_t I2CCheckAlive(uint8_t address)
346373 }
347374 else
348375 {
349- retVal = 4 ;
376+ retVal = 5 ;
350377 }
351378 }
352379 }
353380
381+ _I2CCheckAlive_sendstop :
354382 // send stop
355383 TWCR = (1 << TWINT ) | (1 << TWEN ) | (1 << TWSTO ); // Send STOP condition
356384 _delay_ms (1 );
357385
386+ _i2cIsRunning = 0 ;
358387 return retVal ;
359388}
0 commit comments