本主题介绍如何使用 My.Computer.Ports
Visual Basic 从计算机的串行端口接收字符串。
从串行端口接收字符串
初始化返回字符串。
Dim returnStr As String = ""
确定应提供字符串的串行端口。 此示例假定为
COM1
.使用
My.Computer.Ports.OpenSerialPort
方法获取对端口的引用。 有关详细信息,请参阅 OpenSerialPort。即使应用程序生成异常,该
Try...Catch...Finally
块也允许应用程序关闭串行端口。 处理串行端口的所有代码都应出现在此块中。Dim com1 As IO.Ports.SerialPort = Nothing Try com1 = My.Computer.Ports.OpenSerialPort("COM1") com1.ReadTimeout = 10000 Catch ex As TimeoutException returnStr = "Error: Serial Port read timed out." Finally If com1 IsNot Nothing Then com1.Close() End Try
创建一个
Do
循环,用于阅读文本行,直到没有更多行可用。Do Loop
ReadLine()使用该方法从串行端口读取下一行可用的文本。
Dim Incoming As String = com1.ReadLine()
使用
If
语句来判断ReadLine()方法是否返回Nothing
(这意味着没有更多文本可供使用)。 如果返回Nothing
,退出Do
循环。If Incoming Is Nothing Then Exit Do End If
向
Else
语句添加一个If
块,以便在字符串被实际读取的情况下进行处理。 块从串行端口获取字符串并将其追加到返回字符串中。Else returnStr &= Incoming & vbCrLf
返回字符串。
Return returnStr
示例:
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com1 As IO.Ports.SerialPort = Nothing
Try
com1 = My.Computer.Ports.OpenSerialPort("COM1")
com1.ReadTimeout = 10000
Do
Dim Incoming As String = com1.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com1 IsNot Nothing Then com1.Close()
End Try
Return returnStr
End Function
此代码示例也可作为 IntelliSense 代码片段。 在代码片段选取器中,它位于 连接和网络中。 有关详细信息,请参阅 代码片段。
编译代码
此示例假定计算机正在使用 COM1
。
可靠的编程
此示例假定计算机正在使用 COM1
。 为了提高灵活性,代码应允许用户从可用端口列表中选择所需的串行端口。 有关详细信息,请参阅 “如何:显示可用的串行端口”。
此示例使用一个 Try...Catch...Finally
块来确保应用程序关闭端口并捕获任何超时异常。 有关详细信息,请参阅 Try...Catch...Finally 语句。