Serial Port Packed Message Programing

Serial Port Packed Message Programing

Emc2

JF-Expert Member
Joined
Sep 26, 2011
Posts
16,808
Reaction score
16,953
Nawaombeni anayeweza tafadhari.

I have the Manual of Programming protocol, but when I write code vb.net returns error message.


The following is the table structure of bytes array

minus.gif
Collapse | Copy Code
position 1 2 3 4 5 6 7 8

Name SOH LEN SEQ CMD DATA Post-amble BCC ETX

Lenth/bytes 1 1 1 1 0-200 1 4 1

Value (01h) (20h-FFh) (20h-FFh) (20h-FFh) (20h-FFh) (05h) (30h-3Fh) (03h)
Abbreviations:
“SOH”- (Start Of Heading) start of packed message
“LEN”- total number of bytes from position 2 to position 6, plus fixed offset of 20h.
“SEQ”- serial number of packet. SLAVE puts the same “SEQ” in the reply message. In case when SLAVE receives a message with the same “SEQ”and “CMD” like the last correctly received message, the device ignores the message and repeats the last packet sent to the HOST.
“CMD” – code of command
“DATA”- data, according to the command. If there is no data, the length field is zero.
“BCC” – control sum(0000h-FFFFh). Sum of data bytes from position 2 to position 6. The control sum is transferred in ASCІІ type (12АВ is transferred as 31h 32h 3Аh 3Вh).
“ETX” – (End of TeXt) end of packed message.
Codes sample:
minus.gif
Collapse | Copy Code
Public Class Form1

Private WithEvents sp As System.IO.Ports.SerialPort
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each y As String In System.IO.Ports.SerialPort.GetPortNames
Me.ComboBox1.Items.Add(y)
Next
sp = New IO.Ports.SerialPort("COM4")
sp.StopBits = IO.Ports.StopBits.One
sp.BaudRate = 9600
sp.DataBits = 8
sp.Parity = IO.Ports.Parity.None
sp.Handshake = IO.Ports.Handshake.None
sp.Open()
Dim by As Byte = &H20
' MsgBox(&H20)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim By(9) As Byte
By(0) = 1
By(1) = &H2 + &H20
By(2) = &H58
By(3) = &H45
By(4) = &H5
Dim S As String = Hex(&H58 Xor &H45)
' MsgBox(S)
By(5) = &H30
By(6) = &H30
By(7) = &H31
By(8) = &H3D
By(9) = &H3
sp.Write(By, 0, By.Length - 1)
' MsgBox(sp.ReadByte)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub sp_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
Dim rec As System.IO.Ports.SerialPort = sender
MsgBox(Hex(rec.ReadByte))
End Sub
End Class
 
Back
Top Bottom