vb比较来自串口的回复

时间:2018-10-18 08:10:52

标签: vb.net

如何通过将RESULT文本框“ OK”与REPLY文本框“ OK”进行比较来使REF文本框显示“ PASS”。

我的问题是RESULT文本框与REPLY文本框相同,但REF文本框显示为“ NG”。它应该在RESULT文本框中显示“通过”

Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel

Public Class Form1
    Delegate Sub SetTextCallBack(ByVal [text] As String)

    Private Sub writeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles writeButton.Click

        SerialPort1.Close()
        SerialPort1.PortName = "COM5"
        SerialPort1.BaudRate = "9600"
        SerialPort1.Open()
        SerialPort1.Write(inputTextBox.Text & vbCr)

        If REPLYtxtBox.Text = REFtxtBox.Text Then
            RESULTtxtBox.Text = "PASS"
        Else
            RESULTtxtBox.Text = "NG"
        End If

    End Sub

    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        ReceivedText(SerialPort1.ReadExisting())

    End Sub

    Private Sub ReceivedText(ByVal [text] As String)
        If Me.REPLYtxtBox.InvokeRequired Then
            Dim x As New SetTextCallBack(AddressOf ReceivedText)
            Me.Invoke(x, New Object() {(text)})
        Else
            Me.REPLYtxtBox.Text &= [text]
        End If
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

  SerialPort1.Write(inputTextBox.Text & vbCr)

  If REPLYtxtBox.Text = REFtxtBox.Text Then

您在比较接收到的文本之前有机会接收,在9600bps和串行端口开销下,单个字符将花费> 1ms的时间到达,但是您将在下一个语句中进行检查,这将以微秒为单位。

您需要将支票移动到收到数据后(DataReceived事件处理的一部分)。