B4R Code Snippet I2C Address Scanner

Discussion in 'B4R Code Snippets' started by rwblinn, Feb 2, 2017.

  1. rwblinn

    rwblinn Well-Known Member Licensed User

    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
    Code:
    Scanning started...
    I2C device found at 
    address0x76 (118)
    Scanning completed.
    Snippet
    Code:
    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(1As 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 = 0Then
         
    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
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice