代码之家  ›  专栏  ›  技术社区  ›  Mawg says reinstate Monica

为什么这个代码不能打开串口?

  •  0
  • Mawg says reinstate Monica  · 技术社区  · 14 年前
    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
    

    1 回复  |  直到 14 年前
        1
  •  2
  •   ChrisW    14 年前

    拒绝访问可能意味着已被另一个应用程序打开。

    例如,您是否能够使用另一个已知良好的应用程序打开端口 Hyperterminal ?

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

    Portmon 可用于确定哪个其他进程(如果有)已打开该端口。