我有编程手册协议,但是当我编写代码时,vb.net会返回错误信息。
以下是字节数组的表结构
职位1 2 3 4 5 6 7 8
名称SOH LEN SEQ CMD DATA Post-amble BCC ETX
Lenth / bytes 1 1 1 1 0-200 1 4 1
值(01h)(20h-FFh)(20h-FFh)(20h-FFh)(20h-FFh)(05h)(30h-3Fh)(03h)
缩写:
“SOH” - (标题开头)打包邮件
“LEN” - 从位置2到位置6的总字节数加上固定偏移量20h。
“SEQ” - 数据包的序列号。 SLAVE在回复消息中放置相同的“SEQ”。在SLAVE的情况下 收到与上次正确接收的消息相同的“SEQ”和“CMD”的消息,设备忽略 消息并重复发送到主机的最后一个数据包。
“CMD” - 命令代码
“DATA” - 数据,根据命令。如果没有数据,则长度字段为零。
“BCC” - 控制总和(0000h-FFFFh)。从位置2到位置6的数据字节总和。控制和是 以ASCІІ类型转移(12А被转移为31h32h3Аh3Вh)。
“ETX” - (TeXt结束)打包邮件结束。
代码示例:
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
结束班
答案 0 :(得分:0)
Annael你可能会这样做,通过调用更新函数并给出500毫秒的延迟将有所作为。现在,在接收数据时,您可以接收输入数据
Dim inputData As String = ""// Declare this as a global variable in the program
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)//the code you have written to add Serial ports
SerialPort1.PortName = ComboBox1.Text//this will access your com port as your button
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim by As Byte = &H20
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
SerialPort1.BaudRate = 115200
SerialPort1.Open()
SerialPort1.Write(By)
Private Sub SerialPort1_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Threading.Thread.Sleep(500) ' 500ms delay induced to receive the email
inputData = SerialPort1.ReadExisting 'or SerialPort1.ReadLine
Me.Invoke(New EventHandler(AddressOf DoUpdate))
Public Sub DoUpdate()
MsgBox(inputData)