Snippet to scan for I2C (Inter-Integrated Circuit) devices. Helpful to obtain the connected I2C device(s) address. The address range is 0 and 127. Reference. Libraries: rWire, rRandomAccessFile
Example output
Snippet
Example output
B4X:
Scanning started...
I2C device found at address: 0x76 (118)
Scanning completed.
B4X:
Sub Process_Globals
Public Serial1 As Serial
Public Wire As WireMaster
Private wireerror As Byte = 0
Private deviceaddress As Byte
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Wire.Initialize
Scanning
End Sub
Private Sub Scanning
Private bc As ByteConverter
Dim b(1) As Byte
Dim devices As Int
Log("Scanning started...")
devices = 0
For i = 0 To 127
deviceaddress = i
RunNative("icwirebegintransmisson", deviceaddress)
RunNative("icwireendtransmisson", Null)
b(0) = deviceaddress
If wireerror = 0 Then
Log("I2C device found at address: 0x", bc.HexFromBytes(b), " (", deviceaddress, ")")
devices = devices + 1
End If
If wireerror = 4 Then
Log("I2C device unknown at address: 0x", bc.HexFromBytes(b), " (", deviceaddress, ")")
End If
Next
If (devices = 0) Then
Log("No I2C devices.")
End If
Log("Scanning completed.")
End Sub
#if C
#include <Wire.h>
void icwirebegintransmisson (B4R::Object* o) {
Wire.beginTransmission(b4r_main::_deviceaddress);
}
void icwireendtransmisson (B4R::Object* o) {
b4r_main::_wireerror = Wire.endTransmission();
}
#End if