Hi,
an Arduino is connected to a PC with B4J server.
The B4J Server sends data using the serial connection and asyncstream.write.
The Arduino is also using Asyncstream and is waiting till new data comes in.
When new data received, the Arduino takes action and replies back to the B4J server.
B4R Code
Handle new data received from the B4J server. Either character 1 or 2:
The Arduino replies back to the B4J server in JSON format using asyncstream write:
B4J Code
Write data via the asyncstream to the Arduino:
Handling the incoming data received from the Arduino:
Questions:
an Arduino is connected to a PC with B4J server.
The B4J Server sends data using the serial connection and asyncstream.write.
The Arduino is also using Asyncstream and is waiting till new data comes in.
When new data received, the Arduino takes action and replies back to the B4J server.
B4R Code
Handle new data received from the B4J server. Either character 1 or 2:
B4X:
Sub Astream_NewData (Buffer() As Byte)
Log("Astream Received: ", Buffer, " = ", Buffer(0))
Dim p As UInt = Buffer(0)
If p = 49 Or P = 50 Then MoveCraneArm(p - 48)
End Sub
The Arduino replies back to the B4J server in JSON format using asyncstream write:
B4X:
Sub MoveCraneArm
...
Dim s As String
s = "{""Angle"":"
AStream.Write(s.GetBytes)
s = NumberFormat(ServoArmAnglePos,0,0)
AStream.Write(s.GetBytes)
s = "}"
AStream.Write(s.GetBytes)
...
B4J Code
Write data via the asyncstream to the Arduino:
B4X:
Public Sub AStream_WriteData(data As String)
Log($"AStream_WriteData: ${data}"$)
AStream.Write(data.GetBytes("UTF8"))
End Sub
Handling the incoming data received from the Arduino:
B4X:
Sub AStream_NewData(Buffer() As Byte)
Dim data As String = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
Log($"AStream_NewData: ${data}"$)
...
Questions:
- When using above, the B4J server is constantly receiving weird characters instead of expected JSON string. What could the cause be? The COM parameter are equal.
- In the B4R code is it required to set up a timer or looper to check if new data comes in OR is the async new data sub enough of handling that?