5,692,513 members and growing! (15,841 online)
Email Password   helpLost your password?
Languages » VB.NET » General     Intermediate License: The Code Project Open License (CPOL)

COM port made simple with VB.NET

By WillemM

Using the com port in windows, using any .NET Language
VBWindows, .NET, .NET 1.0, .NET 1.1, Win2K, WinXP, Win2003VS.NET2002, VS.NET2003, Visual Studio, Dev

Posted: 4 Oct 2003
Updated: 4 Oct 2003
Views: 153,106
Bookmarked: 55 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
28 votes for this Article.
Popularity: 5.11 Rating: 3.53 out of 5
3 votes, 10.7%
1
1 vote, 3.6%
2
4 votes, 14.3%
3
10 votes, 35.7%
4
10 votes, 35.7%
5

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)

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.

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.

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.

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)

About the Author

WillemM


WillemM is a 23 year old software developer working for Info Support. He loves new technology and spends most of his free time finding new ways to do things with his computer.
Occupation: Web Developer
Location: Netherlands Netherlands

Other popular VB.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 57 (Total in Forum: 57) (Refresh)FirstPrevNext
QuestionI no nothing about codememberelmerjfudd22:16 19 Jul '08  
Generalcan't open the comport! (Errorcode :2) [modified]memberairbase23:29 9 Sep '07  
GeneralHow to use this class in VS 2005memberBrad Wick7:47 12 Aug '07  
GeneralRe: How to use this class in VS 2005memberWillemM8:10 12 Aug '07  
Generalprocess Byte() codememberxds200021:42 25 Nov '06  
GeneralRe: process Byte() codememberTrevorWJ3:25 1 Mar '07  
GeneralUsing COM Port with ASP.NETmemberajsri7722:40 7 Jun '06  
Generalwhere to start?memberweandee0:13 15 Dec '05  
GeneralRe: where to start?memberChetna Sharma23:45 9 May '06  
Generaladd methodmemberalavitiricchiarazio1:52 19 Oct '05  
GeneralRe: add methodmemberWillemM3:27 19 Oct '05  
GeneralRe: add methodmemberHusamOthman2:01 25 Dec '05  
General'MeinDesign.RS232.hPort' is not accessible in this context because it is 'Private'.memberBrian_Murphy3:41 13 Aug '05  
GeneralRe: 'MeinDesign.RS232.hPort' is not accessible in this context because it is 'Private'.memberWillemM10:10 14 Aug '05  
Generalunder .NET Compact Frameworkmemberpurpal15:07 11 Apr '05  
GeneralRe: under .NET Compact FrameworkmemberWillemM4:18 12 Apr '05  
Generalcontrol two com ports (near) simultaneously?memberEmily Fox3:23 19 Jan '05  
GeneralRe: control two com ports (near) simultaneously?memberWillemM4:53 19 Jan '05  
GeneralThanks!memberBrock Noland15:15 4 Jan '05  
GeneralRe: Thanks!memberWillemM23:55 4 Jan '05  
GeneralRe: how to read variable number of bytes on the com portmemberWillemM23:58 4 Jan '05  
GeneralRe: how to read variable number of bytes on the com portmemberWillemM21:43 5 Jan '05  
GeneralRe: how to read variable number of bytes on the com portmemberWillemM21:51 5 Jan '05  
GeneralRe: how to read variable number of bytes on the com portmemberpapaavola4:54 27 Apr '05  
GeneralRe: how to read variable number of bytes on the com portmemberDahoolio5:27 18 Mar '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 4 Oct 2003
Editor: Nishant Sivakumar
Copyright 2003 by WillemM
Everything else Copyright © CodeProject, 1999-2008
Web13 | Advertise on the Code Project