Android Question Connect to BLE heart rate monitor

csjoe72

Member
Licensed User
Longtime User
I try to connect my heart rate monitor with this code (in starter module):

B4X:
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    Dim Manager As BleManager2
    Dim bc As ByteConverter
    Dim HEART_RATE_SERVICE As String = "180d"
    Dim HEART_RATE_MEASUREMENT As String = "2a37"
    Dim firstRead As Boolean
End Sub

Sub Service_Create
    HEART_RATE_SERVICE = UUID(HEART_RATE_SERVICE)
    HEART_RATE_MEASUREMENT = UUID(HEART_RATE_MEASUREMENT)
    Manager.Initialize("manager")
    Log("Service_Create")
End Sub

Sub Manager_StateChanged (State As Int)
    Log($"StateChanged: ${State}"$)
    If State = Manager.STATE_POWERED_ON Then
        Log("Manager.Scan")
        Manager.Scan(Array(HEART_RATE_SERVICE))
    End If
End Sub

Sub Manager_DeviceFound (Name As String, DeviceId As String, AdvertisingData As Map, RSSI As Double)
    Log("Manager_DeviceFound")
    Manager.StopScan
    Log($"DeviceFound: ${Name}"$)
    Manager.Connect(DeviceId)
End Sub

Sub Manager_Connected (Services As List)
    Log("Connected")
    firstRead = True
    Manager.ReadData(HEART_RATE_SERVICE)
End Sub

Sub Manager_DataAvailable (ServiceId As String, Characteristics As Map)
    If firstRead Then
        firstRead = False
        Manager.SetNotify(HEART_RATE_SERVICE, HEART_RATE_MEASUREMENT, True)
        Return
    End If
   
    Dim b() As Byte = Characteristics.Get(HEART_RATE_MEASUREMENT)
    Dim hrLength As Int = 1 + Bit.UnsignedShiftRight(b(0), 7)
    Dim rate As Int
    If hrLength = 1 Then
        rate = Bit.And(0xff, b(1))
    Else
        Dim r() As Byte = Array As Byte(b(1), b(2))
        rate = bc.IntsFromBytes(r)(0)
    End If
    Log($"Rate: ${rate}"$)
End Sub

Sub UUID(id As String) As String
    Return "0000" & id.ToLowerCase & "-0000-1000-8000-00805f9b34fb"
End Sub

I got the following logs:
Service_Create
StateChanged: 12
Manager.Scan

Next steps are always missing: device found, connect and receive data
The heart rate monitor works with other apps, so I have a mistake.
 
Last edited:
Cookies are required to use this site. You must accept them to continue using the site. Learn more…