我正在创建一个新程序,以通过串行rs232与使用专有通信协议的设备进行通信。
我正在使用SerialPort1_DataReceived处理程序,但是它似乎不起作用。
这些是串行端口的设置:
SerialPort1.PortName = ComboBox1.Text
SerialPort1.BaudRate = ComboBox2.Text
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
SerialPort1.DataBits = 8
SerialPort1.Encoding = System.Text.Encoding.GetEncoding("Windows-1252")
SerialPort1.ReadTimeout = 1
SerialPort1.WriteTimeout = 500
SerialPort1.DtrEnable = Enabled
我也尝试过这种方法:
Dim buffRecei As Byte() = New Byte(SerialPort1.BytesToRead) {}
SerialPort1.Read(buffRecei, 0, buffRecei.Length)
stringInput = BitConverter.ToString(buffRecei)
但它也不起作用
现在,当它接收数据时,我使用&将其附加到字符串中,但是我想要一个解决方案,一旦缓冲区中接收到所有字符串,我就给我完整的字符串。
Private Sub SerialPort1_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim numBytes As Integer = SerialPort1.BytesToRead
Dim buffer(numBytes - 1) As Byte
SerialPort1.Read(buffer, 0, numBytes)
stringInput &= (BitConverter.ToString(buffer))
ReceivedText(stringInput.Replace("-", ""))
End Sub
我还使用了stringInput.Replace("-", ""))
,因为有时在字符串中有-并且我不知道为什么
来自串行的输入类似于“ 346586A9B2C0” 我希望一旦收到充分的刺痛就可以得到完整的琴弦,而不是一目了然
这是字符串在文本框中显示的部分
Private Sub ReceivedText(ByVal [text] As String) 'input from ReadExisting
If Me.RichTextBox2.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.RichTextBox2.Text = [text]
End If
End Sub