我正在编写一个与微控制器通信的Windows窗体。 加载winform后,它应自动检测微控制器连接的位置。
我在做的是:
- Get the names of the available ports
- with a loop through these names :
- assign the port name to the serial port instance in the form
- send a command for the detection
- wait some time
- check if some text has been received
- compare the received message to the identification message
- if it is the right one break the loop and return the result, if not
continue
以下是该功能的代码。我正在使用 thread.sleep 方法。但是这个功能不起作用,当它在那里时我没有检测到它。
你能告诉我这个功能有什么问题吗?时间延迟会阻止接收吗?我应该如何改善它?
加载表单后,此函数在开头处于执行状态。如果我找不到端口,那么任何事情都无法继续。另一方面,在执行的那个阶段我没有其他线索需要考虑。我考虑过 DatarRceived 事件,但在此阶段没有意义,它会在检测到正确的端口后激活。 请让我知道你的想法
谢谢
Public Function connect(testport As SerialPort, recognizeText As String, userCommand As String) As Boolean
Dim intReturnASCII As Integer = 0
Dim charReturnValue = Chr(intReturnASCII)
Dim returnMessage As String = ""
Dim count As Integer = 0
Dim ports As String() = IO.Ports.SerialPort.GetPortNames
If testport.IsOpen Then
testport.Close()
End If
Try
For Each newport As String In ports
testport.PortName = newport
testport.Open()
testport.Write(STX & userCommand & ETX)
Thread.Sleep(200) ' stop the userform and wait for the reception of the response
count = testport.BytesToRead
While count > 0
intReturnASCII = testport.ReadByte
returnMessage = returnMessage + Convert.ToChar(intReturnASCII)
count -= 1
End While
testport.Close()
XMCPort = newport ' Danach instantiate the serial port publicly with port name , is true instantiate
If returnMessage.Contains(recognizeText) Then
Return True
End If
Next
Return False
Catch ex As Exception
Return False
End Try
count = 0
returnMessage = ""
End Function