Page 1 of 1
I2C device on bus

Posted:
Wed Apr 11, 2018 4:49 pm
by AndrewB
Is there a way to check if an I2C device is on the bus?
I have four devices on the bus and three may be removed at some point .
I want to be able to check and count the three if attached.
thanks
Re: I2C device on bus

Posted:
Wed Apr 11, 2018 6:33 pm
by Jerry Messina
Yes.
Send the address byte + WR and check to see if you get an acknowledge.
If the device recognizes its address it'll pull SDA low during the ninth clock. Otherwise, SDA will remain high.
You can terminate the transaction right after reading the ACK bit (so that would be START - ADDR+WR - STOP).
Re: I2C device on bus

Posted:
Wed Apr 11, 2018 8:12 pm
by AndrewB
Ok
Sorry but I could not find any examples on the site.
Do I do
devices = 0
I2C.Start()
I2C.WriteByte(I2C_device + 1)
if I2C.Acknowledge(IsAcknowledge) = true then
devices = devices + 1
Re: I2C device on bus

Posted:
Wed Apr 11, 2018 11:30 pm
by Jerry Messina
Not quite.
The Acknowledge() function is for sending an ack, not reading one. To read it just look at the NotAcknowledged boolean.
Also, the RD_WRN flag in bit0 of the I2C slave address byte is RD=1, WR=0, so send the address with nothing added to it.
More like this...
- Code: Select all
devices = 0
I2C.Start()
I2C.WriteByte(I2C_device)
I2C.Stop()
// check NotAcknowledged flag to see if device responded
if (I2C.NotAcknowledged = I2C.IsAcknowledge) then
devices = devices + 1
endif
Re: I2C device on bus

Posted:
Thu Apr 12, 2018 5:35 pm
by AndrewB
I get an error for "if (I2C.NotAcknowledged = I2C.IsAcknowledge) then" as Incompatible types
Re: I2C device on bus

Posted:
Thu Apr 12, 2018 7:59 pm
by Jerry Messina
Try casting IsAcknowledge to a Boolean type
- Code: Select all
if (I2C.NotAcknowledged = cbool(I2C.IsAcknowledge)) then
You could also just check that NotAcknowledged = false, but that always screws with my head. NotAcknowledged = false when the line is low, so that means you got an ack. I suppose you should think of it as "NotAcknowledged is true, so you didn't get an ack".
Clear as mud, right?
Re: I2C device on bus

Posted:
Tue Jul 24, 2018 10:22 am
by AndrewB
Thanks Jerry.
I ended up just noting if 255 was read when checking as this showed that the device was not present.
Seemed to work OK.
I