Click here to Skip to main content
15,868,419 members
Articles / Programming Languages / Visual Basic
Article

COM port made simple with VB.NET

Rate me:
Please Sign up or sign in to vote.
4.12/5 (30 votes)
4 Oct 2003CPOL2 min read 372K   7.1K   75   60
Using the com port in windows, using any .NET Language

Introduction

This article is about controlling the com port in windows. You can't just tell the computer to open the com port like you would with Pascal or C++ in DOS. But there are still some tricks that makes it possible to open and use the com port. The only thing is, you will need to know something about windows - Win2k has a HAL (Hardware Abstraction Layer).

First of all, windows 2000, windows xp and windows 2003 have protected hardware access. This is the HAL. Very useful when it comes to security, but for programmers like me it's a nightmare. I found a solution: Let windows do the job for you.

How did I make this?

I used some basic windows function for my com port controlling functionality:

  • CreateFile
  • ReadFile
  • WriteFile
  • CloseHandle
  • BuildCommDCB
  • SetCommState

You can find these functions in the old VB6 API Viewer program (Or you might take a look in the source of course).

I simply told windows to do the hardware controlling for me. I will trick my program that the com port is a file. This is made possible through the Windows API Functions I use.

The code

The first function of my code is the open function. The function will be trying to make a com port handle. After that I check if the handle is correct. If the handle is ok, I will continue by making a DCB Structure instance ready for use. With this structure we can control all comport settings. (I will only use, speed, parity, stop bits and data bits)

VB.NET
Public Sub Open(ByVal portname As String, _
        ByVal Spd As Integer, ByVal Pty As enumParity, _
        ByVal Dtb As Integer, ByVal Stp As enumStopBits)

        Dim m_CommDCB As String
        Dim m_Baud As String
        Dim m_Parity As String
        Dim m_Data As String
        Dim m_Stop As Byte

        hPort = CreateFile(portname, GENERIC_READ + GENERIC_WRITE, _
              0, 0, OPEN_EXISTING, 0, 0)

        If hPort < 1 Then
            Throw New Exception("Can't open the comport! (Errorcode :" _
                  & GetLastError().ToString() & ")")
        End If

        m_Baud = Spd.ToString()
        m_Parity = PARITYSTRING.Substring(Pty, 1)
        m_Data = Dtb.ToString()
        m_Stop = Stp

        m_CommDCB = String.Format("baud={0} parity={1} data={2} stop={3}", _
              m_Baud, m_Parity, m_Data, m_Stop)

        BuildCommDCB(m_CommDCB, dcbPort)

        If SetCommState(hPort, dcbPort) = 0 Then
            Throw New Exception("kan de compoort niet openen(" & _
               GetLastError().ToString() & ")")
        End If

        m_opened = True
End Sub

The next function is the Write Function. This function controls the writing to the com port. I choose to write one byte at a time to the com port since I wanted to control a microcontroller with my com port. But you can change this of course to a multi-byte write function or add an extra function for multi-byte.

VB.NET
Public Sub Write(ByVal data As Byte)
 Dim dt As Byte()
        Dim written As Integer

        dt(0) = data 'We have a multi-byte buffer, which you can of 
                     'course enable...

        If Opened = True Then
            WriteFile(hPort, dt, 1, written, Nothing)
        Else
            Throw New Exception("Comport not opened")
        End If

 dt = Nothing
End Sub
Of course I also want to read from the com port. This is achieved by the read function. For this function the same story as for the Write function with the multi-byte add-on.

VB.NET
Public Function Read() As Byte
        Dim rd As Integer
        Dim ovl As New OVERLAPPED
        Dim dt As Byte()

        dt = Array.CreateInstance(GetType(Byte), 1) 'Initialize the buffer

        If Opened = True Then
            ReadFile(hPort, dt, 1, rd, ovl)
        Else
            Throw New Exception("Comport not opened")
        End If

        Return dt(0)
End Function

At last and more important than the open function we have the Close function. This function closes the com port and releases the system handle to it. If we don't do this in NT4/win2k/xp/2003, we get big problems.

VB.NET
Public Sub Close()
        CloseHandle(hPort)
        hPort = -1
        m_opened = False
End Sub

Conclusion

I hope my english wasn't too bad and my explaination not too chaotic. But above all, I hope you have fun with my com port driver!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Netherlands Netherlands
----

Comments and Discussions

 
QuestionOption Explicit and a Few Gripes Pin
brother.gabriel17-Jul-12 11:09
brother.gabriel17-Jul-12 11:09 
Hello! Thanks for the nice project, but I've got a few gripes! This entire project should not used assumed objects! If we are making code public, it is much better to define our types, especially if other coders are using option explicit - it saves folks from having to cypher everything before trying it out. For example, I assume that these constants are all integers?
VB
Const OPEN_EXISTING = 3
Const GENERIC_READ = &H80000000
Const GENERIC_WRITE = &H40000000

Also, I get a VS warning for "buffer" below, saying that the variable is used before it is assigned a value. Indeed, we are doing a ReadFile with a length of "buffer" - but it has no length defined. Would it be right to add this? : "buffer = Array.CreateInstance(GetType(Byte), 1)"
VB
Public Function Read() As Byte
    Dim buffer As Byte()
    Dim rd As Integer = 0

    If m_opened = True Then
        ReadFile(m_handle, buffer, 1, rd, New OVERLAPPED)
    End If

    If rd > 0 Then Return buffer(0) Else Return 0
End Function

QuestionUSB Port programming Pin
jamith5-Mar-09 23:46
jamith5-Mar-09 23:46 
QuestionI no nothing about code Pin
elmerjfudd19-Jul-08 21:16
elmerjfudd19-Jul-08 21:16 
Generalcan't open the comport! (Errorcode :2) [modified] Pin
airbase9-Sep-07 22:29
airbase9-Sep-07 22:29 
GeneralRe: can't open the comport! (Errorcode :2) [modified] Pin
Member 978238924-Jan-13 1:54
Member 978238924-Jan-13 1:54 
QuestionHow to use this class in VS 2005 Pin
Brad Wick12-Aug-07 6:47
Brad Wick12-Aug-07 6:47 
AnswerRe: How to use this class in VS 2005 Pin
WillemM12-Aug-07 7:10
WillemM12-Aug-07 7:10 
Generalprocess Byte() code Pin
xds200025-Nov-06 20:42
xds200025-Nov-06 20:42 
GeneralRe: process Byte() code Pin
TrevorWJ1-Mar-07 2:25
TrevorWJ1-Mar-07 2:25 
GeneralUsing COM Port with ASP.NET Pin
ajsri777-Jun-06 21:40
ajsri777-Jun-06 21:40 
Questionwhere to start? Pin
weandee14-Dec-05 23:13
weandee14-Dec-05 23:13 
AnswerRe: where to start? Pin
Chetna Sharma9-May-06 22:45
Chetna Sharma9-May-06 22:45 
Generaladd method Pin
alavitiricchiarazio19-Oct-05 0:52
alavitiricchiarazio19-Oct-05 0:52 
GeneralRe: add method Pin
WillemM19-Oct-05 2:27
WillemM19-Oct-05 2:27 
GeneralRe: add method Pin
HusamOthman25-Dec-05 1:01
HusamOthman25-Dec-05 1:01 
General'MeinDesign.RS232.hPort' is not accessible in this context because it is 'Private'. Pin
Brian_Murphy13-Aug-05 2:41
Brian_Murphy13-Aug-05 2:41 
GeneralRe: 'MeinDesign.RS232.hPort' is not accessible in this context because it is 'Private'. Pin
WillemM14-Aug-05 9:10
WillemM14-Aug-05 9:10 
Generalunder .NET Compact Framework Pin
purpal11-Apr-05 14:07
purpal11-Apr-05 14:07 
GeneralRe: under .NET Compact Framework Pin
WillemM12-Apr-05 3:18
WillemM12-Apr-05 3:18 
Questioncontrol two com ports (near) simultaneously? Pin
Emily Fox19-Jan-05 2:23
Emily Fox19-Jan-05 2:23 
AnswerRe: control two com ports (near) simultaneously? Pin
WillemM19-Jan-05 3:53
WillemM19-Jan-05 3:53 
GeneralThanks! Pin
Member 16292864-Jan-05 14:15
Member 16292864-Jan-05 14:15 
GeneralRe: Thanks! Pin
WillemM4-Jan-05 22:55
WillemM4-Jan-05 22:55 
GeneralRe: how to read variable number of bytes on the com port Pin
WillemM4-Jan-05 22:58
WillemM4-Jan-05 22:58 
GeneralRe: how to read variable number of bytes on the com port Pin
WillemM5-Jan-05 20:43
WillemM5-Jan-05 20:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.