B4R Library rESP32Bluetooth - Esp32 Classic Bluetooth

Discussion in 'B4R Libraries' started by Erel, May 21, 2018.

Thread Status:
Not open for further replies.
  1. Erel

    Erel Administrator Staff Member Licensed User

    Very simple to use Bluetooth library for ESP32 modules.

    Note that you need to have a recent version of ESP32 SDK. If you encounter any error then download the complete SDK: https://github.com/espressif/arduino-esp32 and copy it to ESP32 SDK folder:
    C:\Users\<user>\Documents\Arduino\hardware\espressif\esp32

    Instructions:
    1. Initialize a ESP32Bluetooth object. You pass the name and the StateChanged event sub. It returns True if it was successful.

    2. Initialize an AsyncStreams object with bt.Stream. Based on my tests the connection is not 100% stable when you send a lot of data. It is therefore recommended to use non-prefix mode.

    3. The StateChanged event will be raised whenever the connection state changes. AStreams_Error will never be raised.

    Example of Bluetooth chat with an Android device:

    [​IMG]

    The B4A project is attached.

    B4R code:
    Code:
    #Region Project Attributes
       
    #AutoFlushLogs: True
       
    #CheckArrayBounds: True
       
    #StackBufferSize: 600
    #End Region

    Sub Process_Globals
       
    Public Serial1 As Serial
       
    Private bt As ESP32Bluetooth
       
    Private astream As AsyncStreams
    End Sub

    Private Sub AppStart
       Serial1.Initialize(
    115200)
       
    Log("AppStart")
       
    If bt.Initialize("Test1""bt_StateChanged") = False Then
           
    Log("Failed to start Bluetooth")
           
    Return
       
    End If
       astream.Initialize(bt.Stream, 
    "astream_NewData""astream_Error")
    End Sub

    Sub bt_StateChanged (Connected As Boolean)
       
    Log("connected: ", Connected)
    End Sub

    Sub AStream_Error
       
    Log("error")
    End Sub

    Sub AStream_NewData (Buffer() As Byte)
       
    Log("NewData: ", Buffer)
       astream.Write(
    "Echo from ESP32: ")
       astream.Write(Buffer)
       bt.Stream.Flush
    End Sub
     

    Attached Files:

    KMatle, janderkan, Altra and 6 others like this.
  2. Johan Hormaza

    Johan Hormaza Active Member Licensed User

    Well, it's working excellent for me:rolleyes:
     
  3. iCAB

    iCAB Well-Known Member Licensed User

    For those who want to automate the test, this can come in handy

    1. In the B4R project, change AStream_NewData as follows

    Code:
    Sub AStream_NewData (Buffer() As Byte)
        
    Log("NewData: ", Buffer)
        astream.Write(Buffer)
        bt.Stream.Flush
    End Sub

    In the B4A project, you can replace ChatActivity code with the code below.

    With this code you will be able to run 2 different tests:
    1. Test1,
    • Sends a fixed length message and attaches a count value to it.
    • On receive, the message is validated.
    • The count is outputted to the GUI.
    • If the validation fails, an error is displayed and the send loop is terminated

    2. Test2 : To run Test2, type "INC", in the input box before clicking send
    • Test2 increments the length of the message by 1 with every loop until an error is triggered.
    I have noticed that Test2 fails when the message length gets to 101



    Code:
    #Region Module Attributes
        
    #FullScreen: False
        
    #IncludeTitle: True
    #End Region

    'Activity module
    Sub Process_Globals
        
        
    Dim blnSendLoopOn As Boolean = False
        
    Dim iSendCounter As Int
        
            
    'Don't include a "_" in this message
        Dim BaseMessageToSend As String = "0123456789:0123456789:01234567890:0123456789:0123456789:0123456789:01234567890:0123456789"
        
    Dim MsgSent As String = ""
        
        
    Dim pw As PhoneWakeState
        
    Dim blnCounterMode As Boolean = True
        
    End Sub

    Sub Globals
        
    Private txtInput As EditText
        
    Private txtLog As EditText
        
    Private btnSend As Button
    End Sub

    Sub Activity_Create(FirstTime As Boolean)
        
    Activity.LoadLayout("2")
        
        pw.KeepAlive(
    False)
    End Sub

    Public Sub NewMessage (Msg As String)
        
    'LogMessage("You", msg)
        Dim MsgToDisplay As String = ""
        
        
    If blnSendLoopOn = True Then
            
    If blnCounterMode = True Then
                
    Dim Components() As String = Regex.Split("_", Msg )
                
    If Components.Length = 2 Then
                    
    If Components(1) = iSendCounter And Components(0) = BaseMessageToSend Then
                        iSendCounter = iSendCounter + 
    1
                        SendLoop
                        
                        
    If (iSendCounter Mod 50) = 0 Then
                            MsgToDisplay  = 
    "The time is: " & DateTime.Time( DateTime.Now ) &  ", Messages Sent: " & iSendCounter
                            
    Log(MsgToDisplay)
                            LogMessage(
    "",MsgToDisplay)
                        
    End If
                    
    Else
                        blnSendLoopOn = 
    False
                        MsgToDisplay = 
    "Error at:" & iSendCounter
                        LogMessage(
    "", MsgToDisplay)
                        
    Log(MsgToDisplay)
                        
    Log("Sent: " & MsgSent )
                        
    Log("Recv: " & Msg )
                    
    End If
                
    End If
            
    Else
                
    If Msg = MsgSent Then
                    MsgToDisplay = 
    "Received Ok: " & Msg.Length & " Chars"
                    SendLoop
                
    Else
                    MsgToDisplay = 
    "Failed, Received: " & Msg.Length & "Chars" & " Sent: " & MsgSent.Length & "Chars"
                    blnSendLoopOn = 
    False
                
    End If
                LogMessage(
    "", MsgToDisplay)
                
    Log(MsgToDisplay)
                
            
    End If
        
    End If
        
        
    If blnSendLoopOn = False Then
            UpdateButtonText
        
    End If
        
    End Sub



    Sub Activity_Resume
        UpdateState
    End Sub

    Public Sub UpdateState
        btnSend.Enabled = Starter.Manager.ConnectionState
    End Sub

    Sub Activity_Pause (UserClosed As Boolean)
        
    If UserClosed Then
            Starter.Manager.Disconnect
        
    End If
    End Sub

    Sub txtInput_EnterPressed
        
    If btnSend.Enabled = True Then btnSend_Click
    End Sub


    Sub btnSend_Click
        
        
    If txtInput.Text.ToUpperCase = "INC" Then
            blnCounterMode = 
    False
        
    Else
            blnCounterMode = 
    True
        
    End If
        
        iSendCounter = 
    0
        
        
    If blnSendLoopOn = False Then
            MsgSent = 
    ""
            SendLoop
        
    End If
        
        blnSendLoopOn = 
    Not(blnSendLoopOn)
        
        UpdateButtonText
        
    '    Starter.Manager.SendMessage(txtInput.Text)
    '    txtInput.SelectAll
    '    txtInput.RequestFocus
    '    LogMessage("Me", txtInput.Text)
    End Sub

    Sub UpdateButtonText()
        
    If blnSendLoopOn = True Then
            btnSend.Text = 
    "Stop"
        
    Else
            btnSend.Text = 
    "Send"
        
    End If
    End Sub


    Sub SendLoop()
        
    If blnCounterMode = True Then
            MsgSent = BaseMessageToSend & 
    "_" & iSendCounter
        
    Else
            MsgSent = MsgSent & 
    "A"
        
    End If       
        Starter.Manager.SendMessage( MsgSent )
    End Sub





    Sub LogMessage(From As String, Msg As String)
        txtLog.Text = txtLog.Text & From & 
    ": " & Msg & CRLF
        txtLog.SelectionStart = txtLog.Text.Length
    End Sub
     
    Johan Hormaza likes this.
  4. viriato

    viriato Member Licensed User

    Hello
    I am trying the example and i got the following error ..it looks like the mbed.h library is missing

    "C:\Users\fvict\DOCUME~1\B4R\NOUVEA~1\Objects\bin\preproc\ctags_target_for_gcc_minus_e.cpp"
    In file included from C:\Users\fvict\DOCUME~1\B4R\NOUVEA~1\Objects\bin\sketch\B4RDefines.h:22:0,
    from C:\Users\fvict\DOCUME~1\B4R\NOUVEA~1\Objects\src\src.ino:1:
    C:\Users\fvict\Documents\Arduino\hardware\espressif\esp32\libraries\BluetoothSerial/BluetoothSerial.h:8:18: fatal error: mbed.h: No such file or directory
    compilation terminated.
    Using library BluetoothSerial in folder: C:\Users\fvict\Documents\Arduino\hardware\espressif\esp32\libraries\BluetoothSerial (legacy)
    exit status 1
    --------------------------------------------
    Any suggestion will be welcome
    Thanks
     
  5. Erel

    Erel Administrator Staff Member Licensed User

    Have you updated the ESP32 SDK?
     
  6. Toley

    Toley Active Member Licensed User

    MaFu and Erel like this.
  7. viriato

    viriato Member Licensed User

    Hi
    I made the re-install again and I am able to compile now..

    Thank you for the prompt feedback
     
Thread Status:
Not open for further replies.
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