BlueTooth

GiovanniPolese

Well-Known Member
Licensed User
Longtime User
Hi
I am new to Basic4Android. I am a C++ programmer.
I am trying to use a Samsung Galaxy II to connect an instrument on serial Port. I use the SerialExample program with some modification, taking away the timer mechanism and just sending a simple Command (actually an "A") to the instrument. The instrument should answer with an Ascii string. All the data exchange has to be done with Ascii characters. My first test is done with the debugger, and, being the instrument rather "slow" to answer (the answer is not immediate), I send the command and stop the program (with the debugger) allowing the instrument "some time" to answer.This is only very first manual experiment, but, in my opinion, some chars should appear on the Serial port. Instead nothing appears. Can anybody tell me something about?
Thanks in advance.
Giovanni
The code is:
Sub btnSend_Click
If connected Then
Dim s As String
s="A"
TextWriter1.WriteLine(s)
TextWriter1.Flush
Read ' this is actually the renamed timer function
End If
End Sub

Sub Read ' old timer function
If connected Then ' here I wait "a little", to allow the instrument to answer
If TextReader1.Ready Then ' this never happens....
txtLog.Text = txtLog.Text & TextReader1.ReadLine & CRLF
txtLog.SelectionStart = txtLog.Text.Length
End If
End If
End Sub
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
There are several issues with your implementation.
You should either use a Timer or AsyncStreams (better option).
However the main problem is calling TextReader.ReadLine. This method reads the characters until it reaches an end of line character. In your case it will just hang as such a character is not available.
Try reading a single byte instead.
 
Upvote 0

rbsoft

Active Member
Licensed User
Longtime User
I had exactly the same problem communication with a custom device to a serial port.

This code worked for me:

B4X:
Sub Serial1_Connected (Success As Boolean)
   Dim msg As String 
   
   If Success = True Then
      ToastMessageShow("BT connected to " & Serial1.Address, False)
      AStreams.Initialize(Serial1.InputStream,Serial1.OutputStream,"AStreams")
      msg = A"
      SendData(msg)

   Else   'disconnected

      ToastMessageShow("BT disconnected", True)
   End If
End Sub


Sub AStreams_NewData (Buffer() As Byte)
    Dim msg As String
   
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    ToastMessageShow(msg, False)
    Log(msg)
End Sub


Sub SendData(msg As String)
   Dim Buffer() As Byte 
   
   Buffer = msg.GetBytes("UTF8")
   Astreams.Write(Buffer)
End Sub
 
Upvote 0

GiovanniPolese

Well-Known Member
Licensed User
Longtime User
Hi Guys, thanks very much for answers, but no results.
Perharps my question was not clear enough. Forget a possible final "well done" implementation and focus on a bare manual send/receive procedure, which must be done only once in life. Just press a Button and send a String and just receive an answer. In my unlucky experience with communication over serial ports, I had always to suffer. No exception now.. That's why I begin my study in such an "unusual" way. First of all I must understand whether this "parameterless" Serial works, in my case. (I am used with BaudRates etc.) (I have no doubts that may work in general). By the way I observe that, on the other side, there is a strongly parameter oriented device (Use something different from its settings, an nothing works. Hope it doesn't matter with Android. This is a first doubt: Serial works with baudrate oriented devices?). The string I send must be Ascii and followed by CrLf. That's why I used the TextWriter.WriteLine. This, if I don't miss something, should send over the Serial port my ascii command followed by CrLf. (Or not? This a second doubt: if I do, instead, as suggested, String s="A" and convert "s" to bytes, what will be sent over the Serial port?). On the other side, the instrument, if receives a correct command (which is the famous "A"+CrLf) answers "Something"+CrLf. So, if the instrument answers, also the TextReader.ReadLine should not hang up, because the CrLf is present. After my experiments, I am almost sure that the problem is that the command is not correctly sent, and no answer follows. So the reception is not guilty. Moreover the program fails on TextReader.Ready, which is never set, so no byte appears on the other side. Another empirical proof is that the instrument doesn't do any action that follows to commands to which it must not answer, but do something, like moving, for example. In other words, if I send a command "Move"+CrLf, it doesn't move. I also already experienced that, with an external Gps, like you did, the program works and gets data. But this case is different: the Gps (at least mine) sends data continuously, without any request from the phone. This seem to confirm that the problem is on sending. Sorry, I was long, but all may be resumed in:
Which may be the cause that prevents the command to be sent? Could be the Serial mechanism not well suited for this case? Does the TextWriter.WriteLine actually send the Ascii text with CrLf or perhaprs converts it to "something else" that will not be understood by the instrument?
By the way I know that some people working with Java and Android were able to drive same type of instrument.
Thanks a lot for your patience and if you have some other hints, I will be grateful.
Best regards
Giovanni
 
Upvote 0

hdtvirl

Active Member
Licensed User
Longtime User
Giovanni, do you have a second Android device that you could run 'BlueChat' (this application chats over bluetooth and is not of an adult nature !) you could use this application to see exactly what your application is sending out.

Regards

BOB
 
Upvote 0

rbsoft

Active Member
Licensed User
Longtime User
Can you couple your BT GPS receiver with your Android device?

My Androids don't recognize it at all, all of my WindowsMobile devices have no problem with it.

About TextReader.Ready - that didn't work for me either. That's why I followed Erel's advice and used AsynchStreams. That did the job. (Not with the GPS of course, but with another device.)

Rolf
 
Upvote 0

GiovanniPolese

Well-Known Member
Licensed User
Longtime User
Hi Bob and Rolf
thanks for your posts.
Unluckily I don't have another Android device. Yes, my RoyalTech BlueGPS couples with Samsung Galaxy S II, and I saw data arriving. I was not very concentrated on this test, so I don't remember well what I did. If need more details I can retry this experience. On this subject of coupling other devices, I see a very good performance of this phone. Instead I was planning to couple the smartphone with a Toshiba Satellite Pro notebook and.. this is only possible for exchanging files by a predefined application. No serial device is accessible on Toshiba side. At least I saw this, and I don't know whether and how I can disable that Toshiba's application that gains the control of the coupling between smartphone and notebook, so I cannot make exchange tests in a good environment, i.e. the Android smartphone on a side and a not Android device on the other. (Two Android devices should not be the best for understanding..) But, this morning I had a new idea that I submit to you: being Basic4Android Java based, the reason of the fault in communication is that the characters are coded with two bytes and so the famous "A" is not understood, because a single byte character is expected. So the TextWriter.WriteLine sends something that the instrument doesn't understand. Probably the "ToBytes" function will resolve. I will verify to day this hypotesis. If I'll get a positive response, I will let you know.
Thanks to all!
Giovanni
 
Upvote 0

GiovanniPolese

Well-Known Member
Licensed User
Longtime User
Hi to all
it seems that I solved the problem, so I post it for future help. Things were simpler than expected.. as usual. Just focus a little on character representation with bytes.. I used the AsyncStream to send Command represented as Bytes. Then ASyncStream works also for reading. This is a very first result. Here is the code:
Sub Process_Globals
Dim AStreams As AsyncStreams
Dim connected As Boolean
End Sub
Sub Globals
Dim btnSend As Button
Dim txtLog As EditText
Dim txtSend As EditText
End Sub
Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
Serial1.Initialize("Serial1")
End If
Activity.LoadLayout("1")
Activity.AddMenuItem("Connect", "mnuConnect")
Activity.AddMenuItem("Disconnect", "mnuDisconnect")
End Sub
Sub Activity_Resume
If Serial1.IsEnabled = False Then
Msgbox("Please enable Bluetooth.", "")
Else
Serial1.Listen 'listen for incoming connections
End If
End Sub
Sub mnuConnect_Click
Dim PairedDevices As Map ' just one, the first, in my situation
PairedDevices = Serial1.GetPairedDevices
Serial1.Connect(PairedDevices.GetValueAt(0))
End Sub

Sub Serial1_Connected (Success As Boolean)
If Success Then
ToastMessageShow("Connected successfully", False)
AStreams.Initialize(Serial1.InputStream,Serial1OutputStream,"AStreams")
connected = True
Else
connected = False
Msgbox(LastException.Message, "Error connecting.")
End If
End Sub
Sub mnuDisconnect_Click
Serial1.Disconnect
connected = False
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub btnSend_Click ' here is the trick
If connected Then
Dim Cmd(3) As Byte
Cmd(0)=0x41 ' A
Cmd(1)=0x0D ' CR
Cmd(2)=0x0A ' LF
AStreams.Write(Cmd)
End If
End Sub

Sub AStreams_NewData (Buffer() As Byte)
Dim msg As String
msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
ToastMessageShow(msg, False)
Log(msg)
End Sub
 
Upvote 0

rbsoft

Active Member
Licensed User
Longtime User
Glad you got it working!

Rolf
 
Upvote 0

GiovanniPolese

Well-Known Member
Licensed User
Longtime User
Hi Rolf
Thanks for your interest on my problem.

Hi Erel
Anyway, I observe that this Basic4Android is a very nice tool. Quickly solving the communication problem did me optimist on future developments on smartphones. My sincere compliments, though you don't need them..
Giovanni
 
Upvote 0
Top