读书人

SerialPort多串口通信解决思路

发布时间: 2013-01-26 13:47:02 作者: rapoo

SerialPort多串口通信
大概要跟下面10个串口进行通信,是直接在界面上放10个SerialPort控件呢,还是用多线程来做呢。
我不太会多线程,能给点例子吗,谢谢!
[解决办法]
可以,每个控件对应不同的com口,不过每个接收时,都会阻塞主线程的,如果接受很简单,无所谓了,如果复杂,将对接收的内容处理的代码放到线程中
[解决办法]
申明委托来做


Delegate Sub RecieveRefreshMethodDelegate(ByVal [text] As String) '声明委托
Dim RecieveRefresh As New RecieveRefreshMethodDelegate(AddressOf RecieveRefreshMethod) '定义一个委托实例

[解决办法]
全给你去看吧,10个串口太复杂了,用timer控件是不行的
最好使用串口传上来数据,然后机器响应



Sub RecieveRefreshMethod(ByVal str As String) '定义一个实例方法
ShowRecieveData(str)
End Sub

Private Sub ShowRecieveData(ByVal str As String)

Try
ComTxT.Text += str
Catch ex As UnauthorizedAccessException
MsgBox("数据接收或显示错误!", MsgBoxStyle.Information, "提示!")
End Try

End Sub

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

Dim Rxstr As String
Try
clsGlobalVariable.Listening = True

If SerialPort1.BytesToRead > 0 Then

Threading.Thread.Sleep(200)
Rxstr = SerialPort1.ReadExisting
ComTxT.Invoke(RecieveRefresh, Rxstr)
clsGlobalVariable.RecData = ""
clsGlobalVariable.RecData = ComTxT.Text
If XORRR(clsGlobalVariable.RecData) = Mid(clsGlobalVariable.RecData, Len(clsGlobalVariable.RecData) - 4, 2) Then
Debug.Print(Mid(clsGlobalVariable.RecData, Len(clsGlobalVariable.RecData) - 1, 2))
MsgBox(PLCRecErr(Mid(clsGlobalVariable.RecData, Len(clsGlobalVariable.RecData) - 4, 2)))
End If
End If

Catch en As Exception


MsgBox("读数据错误!", MsgBoxStyle.Information, "提示!")
Finally
clsGlobalVariable.Listening = False
End Try

End Sub

读书人网 >VB Dotnet

热点推荐