2010-09-01 4 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 

Quand il court, il montre un seul port COM "COM1". Je suis assuré que l'appareil qui y est attaché est un standard 8, n, 1 et utilise 9 600 bauds.Pourquoi ce code ne peut-il pas ouvrir un port série?

L'exception est "Acess au port COM1 'est refusé". Des idées?

Répondre

2

Accès refusé peut signifier que l'a déjà été ouverte par une autre application.

Êtes-vous en mesure d'ouvrir le port en utilisant une autre application en bon état, par exemple Hyperterminal?

[Parce que si vous n'êtes pas, le problème est pas avec votre code.]

Sinon, je pense que Portmon peut être utilisé pour déterminer quel autre procédé (le cas échéant) a déjà ouvert le port .

+0

Édité à la référence Portmon – ChrisW