我正在开发一个通过笔记本电脑/ PC的USB端口连接RS232的项目。我已经创建了vb.net应用程序。当应用程序第一次加载时,它需要检测串行端口。截至目前,我手动将portname放在serialport的属性中,但如果我部署我的应用程序,如果我使用其他笔记本电脑/ PC,则会出现错误:System.IO.IOException,因为我运行了我的GUI。我想编写自动检测串口,但我不熟悉vb.net中的串口编程。
任何人都可以帮助我吗?谢谢!
这是我的计划的一部分:
Imports System.IO.Ports
Public Class Form1
'Dim myPort As Array
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
'myPort = IO.Ports.SerialPort.GetPortNames()
SerialPort1.Open()
Timer1.Enabled = True
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
'==zigbee sent data to the app====
Console.Beep(3000, 1000) 'high tone buzzer whenever there is a notification received
MsgBox("THERE IS A NOTIFICATION RECEIVED!")
uart_rx = Me.SerialPort1.ReadExisting
toDisplay = toDisplay + uart_rx
flag = 1 'there is a notification sent
End Sub
....
在myPort = IO.Ports.SerialPort.GetPortNames()之后,我不知道下一步该做什么。
答案 0 :(得分:0)
有一个示例显示如何在以下网页上完成此操作:http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx
在示例中,在应用程序与端口通信之前,系统会提示用户输入串行端口设置。
SerialPort.GetPortNames(http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames.aspx)将获取串口的名称。
答案 1 :(得分:0)
我提供了一个列表框,并用系统上的所有端口填充它。用户必须选择com端口,然后将该端口名称分配给串口 代码如下 将SP调暗为字符串
Private Sub frmSelectPort_Load(sender as Object, e as
System. EventArgs) Handles Me. Load
GetSerialPortnames
End Sub
Sub GetSerialPortnames () For Each SP In My. Computer.
SerialPortNames
Listbox1. Items. Add(sp)
End Sub
(Under button click event)
SP =Listbox1. SelectedItem
SerialPort1. PortName=SP
SerialPort1. Open()