Skip to content

twi can be blocking in case of not correctly functioning I2C device #2418

Closed
@jantje

Description

@jantje

I have had multiple compass modules (HMC5883) which get confused after some time of running. Resetting the arduino made the arduino to stop working from time to time.
This article helped me to confirm that twi can get in an endless loop. http://www.megunolink.com/how-to-detect-lockups-using-the-arduino-watchdog/
Basically I compiled my code with a watchdog which dumped the address and then avr-objdump is used to find the watchdog triggering code.
This method (details below) show that following code is running in an endless loop.

  // wait for write operation to complete
  while(wait && (TWI_MTX == twi_state)){
    continue;
  }

I changed the code to this

void delayMicroseconds(unsigned int us); //declare this method from wiring.c
....
...
  uint8_t counter=0;
  // wait for write operation to complete
  while(wait && (TWI_MTX == twi_state)){
    delayMicroseconds(100);
    if(counter++>10)
        {
        //TODO write correct error handling here
        return 5;//error timing out
        }
  }

But as the code states there is some extra error handling needed as otherwise all consequent wire actions fail. I'm also not confident that the timing used is even closely correct as at the time of writing no I2C devices worked in my test setup.

More details on how I know the twi code is the problem
This is objdump of the code
// wait for write operation to complete
while(wait && (TWI_MTX == twi_state)){
4920: 22 23 and r18, r18
4922: 21 f0 breq .+8 ; 0x492c <twi_writeTo+0x78>
4924: 80 91 ab 0d lds r24, 0x0DAB
4928: 82 30 cpi r24, 0x02 ; 2
492a: e1 f3 breq .-8 ; 0x4924 <twi_writeTo+0x70>
continue;
}
This is the report generated by the code mentioned above

Application Monitor

Saved reports: 10
Next report: 7
0: word-address=0x2492: byte-address=0x4924, data=0x0
1: word-address=0x2494: byte-address=0x4928, data=0x0
2: word-address=0x2494: byte-address=0x4928, data=0x0
3: word-address=0x2494: byte-address=0x4928, data=0x0
4: word-address=0x2495: byte-address=0x492A, data=0x0
5: word-address=0x2494: byte-address=0x4928, data=0x0
6: word-address=0x2494: byte-address=0x4928, data=0x0
7: word-address=0x2492: byte-address=0x4924, data=0x0
8: word-address=0x2494: byte-address=0x4928, data=0x0
9: word-address=0x2492: byte-address=0x4924, data=0x0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Architecture: AVRApplies only to the AVR microcontrollers (Uno, etc.)Library: WireThe Wire Arduino libraryType: BugType: DuplicateAnother item already exists for this topic

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions