views:

43

answers:

1
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

When it runs, it shows a single COM port "COM1". I am assured that the device attached to it is a standard 8,n,1 and uses 9,600 baud.

The exception is "Acess to the port 'COM1' is denied". Any ideas?

+1  A: 

Access denied might mean that the has already been opened by another application.

Are you able to open the port using another, known-good application, for example Hyperterminal?

[Because if you're not, then the problem isn't with your code.]

Alternatively, I think that Portmon can be used to determine which other process (if any) has already opened the port.

ChrisW
Edited to reference Portmon
ChrisW