2010-09-01 92 views
0
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'被拒绝”。有任何想法吗?

回答

2

访问被拒绝可能意味着已被其他应用程序打开。

是否可以使用另一个已知良好的应用程序打开端口,例如Hyperterminal

[因为如果你不是,那么问题不在于你的代码。]

另外,我认为Portmon可用于确定哪些过程(如果有的话)已经打开的端口。

+0

编辑参考Portmon – ChrisW 2010-09-01 11:17:43

相关问题