Hi,
based on previous Analog Read Example extended the solution by using the Arduino Ethernet Shield to send temperature data to B4J server and receive confirmation.
Full project (with comments) attached.
//Next will be Analog Read Example using MQTT
B4R Code
B4J Code
based on previous Analog Read Example extended the solution by using the Arduino Ethernet Shield to send temperature data to B4J server and receive confirmation.
Full project (with comments) attached.
//Next will be Analog Read Example using MQTT
B4R Code
B4X:
Sub Process_Globals
Public Serial1 As Serial
Private astream As AsyncStreams
Private TempSensor As Pin
Private TempSensorPinNumber As Byte = 0x0A
Private MeasureTimer As Timer
Private MeasureTimerInterval As ULong = 2
Private eth As Ethernet
Private ethClient As EthernetSocket
Private MacAddress() As Byte = Array As Byte(0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED)
Private ClientIP() As Byte = Array As Byte(192, 168, 0, 99)
Private ServerIP() As Byte = Array As Byte(192, 168, 0, 4)
Private const ServerPort As UInt = 51042
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
TempSensor.Initialize(TempSensorPinNumber, TempSensor.MODE_OUTPUT)
eth.Initialize(MacAddress, ClientIP)
MeasureTimer.Initialize("MeasureTimer_Tick", MeasureTimerInterval * 1000)
EthernetConnect(0)
End Sub
Private Sub MeasureTimer_Tick
Dim rawvoltage As UInt = TempSensor.AnalogRead
Dim volts As Double = rawvoltage/205.0
Dim celsiustemp As Double = 100.0 * volts - 50
If ethClient.Connected Then
Dim s As String = NumberFormat(celsiustemp, 0, 2)
astream.Write(s.GetBytes)
Else
Log("Ethernet not connected")
End If
End Sub
'Connect to the ethernet server. If ok, then start the timer to gather temperature data
Sub EthernetConnect(unused As Byte)
If ethClient.ConnectIP(ServerIP, ServerPort) = False Then
Log("Error: Trying to connect again")
CallSubPlus("EthernetConnect", 1000, 0)
Return
End If
astream.Initialize(ethClient.Stream, "Astream_NewData", "Astream_Error")
MeasureTimer.Enabled = True
End Sub
Sub Astream_NewData (Buffer() As Byte)
Log("Received from server: ", Buffer)
End Sub
Sub Astream_Error
Log("Astream Error")
ethClient.Close
CallSubPlus("EthernetConnect", 1000, 0)
End Sub
B4J Code
B4X:
Sub Process_Globals
Private aStream As AsyncStreams
Private Server As ServerSocket
End Sub
Sub AppStart (Args() As String)
Server.Initialize(51042, "Server")
Server.Listen
StartMessageLoop
End Sub
Sub Server_NewConnection (Successful As Boolean, NewSocket As Socket)
aStream.Initialize(NewSocket.InputStream, NewSocket.OutputStream, "Astream")
Server.Listen
End Sub
Sub Astream_NewData (Buffer() As Byte)
If Not(IsNumber(BytesToString(Buffer, 0, Buffer.Length, "UTF8"))) Then
Log($"${DateTime.Time(DateTime.Now)}: Invalid Data."$)
Else
Log($"${DateTime.Time(DateTime.Now)}: ${BytesToString(Buffer, 0, Buffer.Length, "UTF8")}"$)
End If
aStream.Write("Temperature data received.".GetBytes("UTF8"))
End Sub