SI2C Clock Stretching

General discussion relating to the library modules supplied with the compiler

Moderators: David Barker, Jerry Messina

Post Reply
User avatar
Steven
BETA Tester
Posts: 406
Joined: Tue Oct 03, 2006 8:32 pm
Location: Cumbria, UK

SI2C Clock Stretching

Post by Steven » Mon Oct 15, 2007 4:35 pm

Hello All,

I have been trying to interface to a digital compass module and have been getting the odd false reading. After a bit of searching through documentation and a guide to I2C (very useful reference: http://www.robot-electronics.co.uk/htm/ ... 2c_bus.htm), I decided that it must be due to the slave stretching the clock (i.e. holding it low whilst it finishes its work before sending a byte). I have altered the ShiftIn function of the SI2C module to include a wait for clock stretching, with a timeout:

Code: Select all

{
****************************************************************************
* Name    : ShiftIn (PRIVATE)                                              *
* Purpose : Shift in a byte value, MSB first, sample whilst clock high     *
****************************************************************************
}
Function ShiftIn() As Byte
   Dim Index As Byte
   Dim TimeOut As Byte
   Index = 8
   Result = 0
   Input(SDA)
   Repeat
      High(SCL)
      TimeOut = $FF
      Repeat
         Dec(TimeOut)
         Delay
      Until (SCL = 1 Or TimeOut = 0) // wait for any clock stretching by slave
      Result = Result << 1
      Result.0 = SDA
      Low(SCL)
      Delay
      Dec(Index)
   Until Index = 0
   Output(SDA)
   ClrWDT
End Function
The ClrWDT might need to go inside the loop?

Regards,

Steve

TimB
Posts: 262
Joined: Wed Oct 04, 2006 7:25 am
Location: London UK

Post by TimB » Mon Oct 15, 2007 4:54 pm

Very nice and a good example of why open Libs are great.

I take it it actually works ;)

User avatar
Steven
BETA Tester
Posts: 406
Joined: Tue Oct 03, 2006 8:32 pm
Location: Cumbria, UK

Post by Steven » Mon Oct 15, 2007 5:36 pm

Yes, the results are much better now. I agree - the open libraries are a really excellent feature of Swordfish!!! Thanks Dave! :)

Post Reply