Android Question Android connection to car ODB2

tito

Member
Licensed User
Longtime User
Hi everyone,

I'm developing an app for logging car rides.
user has to insert start time, end time, addresses etc. and also the mileage / amount of distance for the car ride.

My idea is it to read out the mileage directly from the ODB2 interface over bluetooth into the app.

Has anyone an idea or experience with this kind of issue?
-which module?
-open bluetooth possible?
-helpful links?
-experience maybe with this? http://openxcplatform.com/ (they are providing an android library, is it possible to wrap to b4a? :) )


Thx
 

KMatle

Expert
Licensed User
Longtime User
Old example which connects to an OBD scanner and sends some AT commands to establish a connection. You should see an "OK" from the scanner. See other commands to read values or get error codes from the car:

B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: true
    #ApplicationLabel: OBDII Example
    #VersionCode: 1
    #VersionName: V1.0
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

'Activity module
Sub Process_Globals
    Dim serial1 As Serial
    Dim AStream As AsyncStreams

    Dim BTA As BluetoothAdmin
    Private rp As RuntimePermissions
End Sub

Sub Globals
    Dim ScannerMacAddress As String
    Dim ScannerOnceConnected As Boolean
    Dim BTStatus As Label
    Dim ConnectBTN, SendATBtn As Button
    Dim ReplyString As String
End Sub

Sub Activity_Create(FirstTime As Boolean)
    
    serial1.Initialize("Serial")
    
    
    BTA.Initialize("BTA")
    
    BTStatus.Initialize("")
    Activity.AddView(BTStatus,1%x,0%y,98%x,5%y)
    BTStatus.Text="Disconnected"
    
    ConnectBTN.Initialize("Connect")
    Activity.AddView(ConnectBTN,1%x,90%y,98%x,10%y)
    ConnectBTN.Text="Connect"
    
    SendATBtn.Initialize("SendAT")
    Activity.AddView(SendATBtn,1%x,30%y,98%x,10%y)
    SendATBtn.Text="Send At Command"
    
    
End Sub

Sub ShowPairedDevices

    Dim PairedDevices As Map
    PairedDevices = serial1.GetPairedDevices
    Dim l As List
    l.Initialize
    For i = 0 To PairedDevices.Size - 1
        l.Add(PairedDevices.GetKeyAt(i))
    Next
    If l.Size=0 Then
       l.Add("No device(s) found...")
        MsgboxAsync("You need to activate Bluetooth and pair a device manually","No device(s) available")
        Return
    End If
    Dim res As Int
    res = InputList(l, "Choose device", -1) 'show list with paired devices
    If res <> DialogResponse.CANCEL Then
        If l.Get(res)="No device(s) found..." Then
           Return
        Else
           ScannerMacAddress=PairedDevices.Get(l.Get(res)) 'convert the name to mac address and connect
           serial1.Connect(ScannerMacAddress)
          
        End If
    End If
    
End Sub

Sub SendAT_Click
    ReplyString=""
    Dim data As String
    Dim ByteBuffer() As Byte
    
    data = "ATZ" & Chr(13) 'Reset
    ByteBuffer = data.GetBytes("UTF8")
    AStream.Write(ByteBuffer)
    
    Sleep(1000)
    
    data = "ATE0" & Chr(13) 'Echo off
    ByteBuffer = data.GetBytes("UTF8")
    AStream.Write(ByteBuffer)
    
    Sleep(1000)
    
    data = "ATZ" & Chr(13) 'Reset
    ByteBuffer = data.GetBytes("UTF8")
    AStream.Write(ByteBuffer)
    
    
End Sub

Sub Connect_Click
    rp.CheckAndRequest(rp.PERMISSION_ACCESS_COARSE_LOCATION)
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    If Result = False Then
        ToastMessageShow("No permission...", False)
        Return
    End If
    BTA.Enable
    ShowPairedDevices
End Sub

Sub Serial_Connected (success As Boolean)
    If success = True Then
       Log("Scanner is now connected. Waiting for data...")
       AStream.Initialize(serial1.InputStream, serial1.OutputStream, "AStream")
       ScannerOnceConnected=True
       BTStatus.Text="Connected :-)"
    Else
        Log(LastException.Message)
        MsgboxAsync("Could not connect:" & LastException.Message,"Could not connect")
       If ScannerOnceConnected=False Then
          MsgboxAsync("Please switch on the scanner...","Scanner is offline")
          ShowPairedDevices
       Else
           Log("Still waiting for the scanner to reconnect: " & ScannerMacAddress)
        'T.Enabled=True
       End If
    End If
End Sub

Sub AStream_NewData (Buffer() As Byte)
    'Log("Received: " & BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
    ReplyString=ReplyString&BytesToString(Buffer, 0, Buffer.Length, "UTF-8")
    If ReplyString.Contains(">") Then
       MsgboxAsync("Data: " & ReplyString ,"New Data")
       Dim bc As ByteConverter
       Dim b() As Byte = bc.StringToBytes(ReplyString,"UTF-8")
       Log(ReplyString)
       MsgboxAsync("Hex: " & bc.HexFromBytes(b),"Hex")
    End If
End Sub

Sub AStream_Error
    Log("Connection broken...")
    
    AStream.Close
    serial1.Disconnect
    If ScannerOnceConnected=True Then
       'T.Enabled=True
    Else
       ShowPairedDevices
    End If
End Sub

Sub AStream_Terminated
    Log("Connection terminated...")
    AStream_Error
End Sub



Sub BTA_StateChanged (NewState As Int, OldState As Int)
    If NewState=BTA.STATE_OFF Then
       Log("BT is OFF now")
        BTStatus.Text="BT OFF"
    End If
    If NewState=BTA.STATE_TURNING_ON Then
        Log("BT is turning on")
        BTStatus.Text="BT starting"
    End If
    If NewState=BTA.STATE_TURNING_OFF Then
        Log("BT is turning off")
        BTStatus.Text="BT turning OFF"
    End If
    
    
    If NewState = BTA.STATE_ON Then
       Log("BT is ON now")
        BTStatus.Text="BT is ON"
      
    End If
End Sub

Sub Activity_Resume
    Log("Resuming...")
    BTA.Enable
    
    
    'ShowPairedDevices
    If ScannerOnceConnected=True Then
       'T.Enabled=True
    End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    Log ("Activity paused. Disconnecting...")
    AStream.Close
    serial1.Disconnect
    BTA.Disable
    
End Sub
 
Upvote 1

Hanspeter

New Member
Licensed User
Longtime User
Hi everyone,

I'm developing an app for logging car rides.
user has to insert start time, end time, addresses etc. and also the mileage / amount of distance for the car ride.

My idea is it to read out the mileage directly from the ODB2 interface over bluetooth into the app.

Has anyone an idea or experience with this kind of issue?
-which module?
-open bluetooth possible?
-helpful links?
-experience maybe with this? http://openxcplatform.com/ (they are providing an android library, is it possible to wrap to b4a? :) )


Thx
Hi Tito,

Take a look at OBDII protocols here as a guide and hookup details.
Connectivity via TTL UART.

https://www.elmelectronics.com/products/ics/obd/

Kind regards,
Hanspeter.
 
Upvote 0

tito

Member
Licensed User
Longtime User
Thank you all for the hints and code snippets.
Does anyone of you already tried it to work with this kind of hardware?
Any recommended ODB2 scanner?
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
Get a cheap one (9€) first for the first steps. You need to study which commands to send to get e.g. the speed or other values. See the docs for ODB2 on the www. There's no ready solution here in the forum (lot's of work to implement and test everything).
 
Upvote 0
Top