Public Class my_class
Dim WithEvents COMPort As New System.IO.Ports.SerialPort
Public Sub FindReader()
Dim ports As String() = IO.Ports.SerialPort.GetPortNames()
Dim port As String
For Each port In ports
MsgBox(port, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Serial port detecetd")
Next port
If COMPort.IsOpen Then
COMPort.RtsEnable = False
COMPort.DtrEnable = False
COMPort.Close()
System.Threading.Thread.Sleep(200)
End If
COMPort.PortName = "COM1"
COMPort.BaudRate = 9600
COMPort.DataBits = 8
COMPort.Parity = IO.Ports.Parity.None
COMPort.StopBits = IO.Ports.StopBits.One
COMPort.Handshake = IO.Ports.Handshake.RequestToSend
COMPort.ReadTimeout = 2000
COMPort.WriteTimeout = -1
COMPort.NewLine = Chr(13)
COMPort.ReadBufferSize = 12
COMPort.ReceivedBytesThreshold = COMPort.ReadBufferSize
Try
COMPort.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
If COMPort.IsOpen Then
COMPort.RtsEnable = True
COMPort.DtrEnable = True
'Kick start the serial port so it starts reading data.
COMPort.BreakState = True
System.Threading.Thread.Sleep(CInt(11000 / COMPort.BaudRate) + 2) ' Min. 11 bit delay (startbit, 8 data bits, parity bit, stopbit
COMPort.BreakState = False
MsgBox(COMPort.PortName & " opened at " & COMPort.BaudRate.ToString & " baud", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "FindReader()")
End If
End Sub
运行时,它显示一个COM端口“COM1”。我确信连接到它的设备是标准的8,n,1并使用9,600波特。
例外是“进入端口'COM1'被拒绝”。有什么想法吗?
答案 0 :(得分:2)
拒绝访问可能意味着已经被其他应用程序打开了。
您是否可以使用其他已知良好的应用程序打开端口,例如Hyperterminal?
[因为如果你不是,那么问题不在你的代码上。]
或者,我认为Portmon可以用来确定哪个其他进程(如果有的话)已经打开了端口。