Using I2C to scan for devices
Posted: Mon Jun 15, 2020 12:01 pm
Hey guys,
I have been trying to make a simple sub to read all the connected addresses on a I2C bus, the following routine works, but sometimes I get strange results on a serial monitor (as in the bus thinks there's 127 addresses on it?, when there's not), now I don't know if the sub is fully correct with how the I2C works or whether its a device on the bus that spaz-out the bus and gives me the wrong output data to a serial monitor.. If there's any suggestions or recommendations then it would be much appreciated..
I have been trying to make a simple sub to read all the connected addresses on a I2C bus, the following routine works, but sometimes I get strange results on a serial monitor (as in the bus thinks there's 127 addresses on it?, when there's not), now I don't know if the sub is fully correct with how the I2C works or whether its a device on the bus that spaz-out the bus and gives me the wrong output data to a serial monitor.. If there's any suggestions or recommendations then it would be much appreciated..
Code: Select all
dim addrs, error, nDevices as byte
sub ScanForDevices()
for addrs = 1 to 127
i2c.start()
i2c.writebyte(addrs)
i2c.writebyte($20) '<--- the sub doesn't work unless I add this, the value isn't important.
i2c.stop()
If (I2C.NotAcknowledged = true) Then
error = 1 ' no device
Else
error = 0 ' device detected
EndIf
If error = 0 Then ' no error we have found a device.
USART.Write("$", HexToStr(addrs), 13, 10)
Inc(nDevices) ' found a device so add number of device.
End If
Next
If nDevices = 0 Then
USART.Write("No I2C devices found ", DecToStr(nDevices), 13, 10)
Else
USART.Write("Complete found ", DecToStr(nDevices), 13, 10)
End If
nDevices = 0 ' reset
End Sub