Click here to Skip to main content
13,146,014 members (43,459 online)
Click here to Skip to main content
Add your own
alternative version

Stats

267.2K views
59 bookmarked
Posted 16 Apr 2002

How to open a serial COM port in Managed C++

, 16 Apr 2002
Rate this:
Please Sign up or sign in to vote.
How to open a Serial COM port using Managed C++ and loading unmanaged DLLs
<!-- Add the rest of your HTML here -->

Introduction

Many days ago, I was looking for a class in managed C++ that gives me access to the COM port. I was surprised I couldn't find anything to use. There were many classes to use for sockets and files, but none for COM ports.

I tried to use System::IO::File without any success. Actually File::Open gave me an exception. So I went ahead and created a class to handle serial COM ports. Please note I am using DllImport to import the kernel32.dll 

<pre lang=mc++>// Header File __gc class CSerialPort { public: CSerialPort(void); __nogc struct DCB { int DCBlength; int BaudRate; int fBinary; int fParity; int fOutxCtsFlow; int fOutxDsrFlow; int fDtrControl; int fDsrSensitivity; int fTXContinueOnXoff; int fOutX; int fInX; int fErrorChar; int fNull; int fRtsControl; int fAbortOnError; int fDummy2; unsigned short wReserved; unsigned short XonLim; unsigned char ByteSize; //byte unsigned char Parity; // byte unsigned char StopBits; //byte char XonChar; char XoffChar; char ErrorChar; char EofChar; char EvtChar; unsigned short wReserved1; }; bool Open( char *szComPort); void Write(String __gc * buf); String *Read(); void Close(); private: FileStream * m_MyFileStream; StreamWriter * m_MyStreamWriter; StreamReader * m_MyStreamReader; static long GENERIC_READ = 0x80000000L; static long GENERIC_WRITE = 0x40000000L; static int OPEN_ALWAYS = 4; static int FILE_FLAG_NO_BUFFERING = 0x20000000; static int FILE_FLAG_OVERLAPPED = 0x40000000; }; namespace MyKernel { [DllImport("kernel32.dll")] extern bool SetCommState(System::IntPtr hFile, CSerialPort::DCB * lpDBC); [DllImport("kernel32.dll")] extern int CreateFile( char * lpFileName , int dwDesiredAccess, int dwShareMode, IntPtr lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile ); }

Also note that I am creating a new namespace to use the imported functions from kernel32.dll

This is the cpp file:

<pre lang=mc++>CSerialPort::CSerialPort(void) { } bool CSerialPort::Open( char *szComPort) { int handle; handle = MyKernel::CreateFile( szComPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, NULL); try { IntPtr pCom(handle); m_MyFileStream = new FileStream(pCom, FileAccess::ReadWrite, true, 1000, true); } catch (Exception * e ) { Console::WriteLine(e->ToString()); return false; } DCB * CommSettings = new DCB(); CommSettings->DCBlength = sizeof(CommSettings); CommSettings->BaudRate = 38400; CommSettings->ByteSize = 8; CommSettings->Parity = 0; CommSettings->StopBits = 1; MyKernel::SetCommState(m_MyFileStream->get_Handle(), CommSettings); try { m_MyStreamReader = new StreamReader(m_MyFileStream); } catch (Exception * e ) { Console::WriteLine(e->ToString()); return false; } if ( m_MyFileStream->get_CanWrite() ) { try { m_MyStreamWriter = new StreamWriter(m_MyFileStream); } catch (Exception * e ) { Console::WriteLine(e->ToString()); return false; } } return true; } void CSerialPort::Write(String __gc * buf) { try { m_MyStreamWriter->Write(buf); m_MyStreamWriter->Flush(); } catch (Exception * e ) { Console::WriteLine(e->ToString()); } } String * CSerialPort::Read() { String *buf; buf = m_MyStreamReader->ReadLine(); return (buf); } void CSerialPort::Close() { m_MyStreamWriter->Close(); m_MyStreamReader->Close(); m_MyFileStream->Close(); }

To use it:

CSerialPort * pSerial = new CSerialPort;

pSerial->Open(S"COM2:");
Console::WriteLine(pSerial->Read());

We open COM port 2 and we wait to read a LINE with \r\n or \n. If you waiting for bytes you need to change m_MyStreamReader->ReadLine() to m_MyStreamReader->Read().

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Albert Pascual
Web Developer
United States United States
Al is just another Software Engineer working in C++, ASp.NET and C#. Enjoys snowboarding in Big Bear, and wait patiently for his daughters to be old enough to write code and snowboard.

Al is a Microsoft ASP.NET MVP

Blog

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralI cannot SetCommState to return true. Pin
netlogging4-Apr-08 5:13
membernetlogging4-Apr-08 5:13 
QuestionException by FileStream Pin
strizi2-Nov-07 0:16
memberstrizi2-Nov-07 0:16 
QuestionRe: Exception by FileStream Pin
netlogging4-Apr-08 5:46
membernetlogging4-Apr-08 5:46 
QuestionSample code Pin
strizi2-Nov-07 0:14
memberstrizi2-Nov-07 0:14 
GeneralHi Pin
temikasali6-Aug-07 20:17
membertemikasali6-Aug-07 20:17 
Generalcode problem! Pin
Nenica16-Jun-04 13:15
memberNenica16-Jun-04 13:15 
GeneralRe: code problem! Pin
HristoBojkov20-Apr-05 22:18
memberHristoBojkov20-Apr-05 22:18 
GeneralWin32 Application Pin
Nenica18-Feb-04 10:28
memberNenica18-Feb-04 10:28 
GeneralRe: Win32 Application Pin
surajt14-May-04 9:00
membersurajt14-May-04 9:00 
GeneralRe: Win32 Application Pin
Nenica16-Jun-04 13:12
memberNenica16-Jun-04 13:12 
GeneralRe: Win32 Application Pin
Sharingan_Rasengan10-Jul-06 18:05
memberSharingan_Rasengan10-Jul-06 18:05 
GeneralRe: Win32 Application Pin
Sharingan_Rasengan10-Jul-06 18:05
memberSharingan_Rasengan10-Jul-06 18:05 
GeneralRe: Win32 Application Pin
mertadin18-Jul-06 22:19
membermertadin18-Jul-06 22:19 
GeneralRe: Win32 Application Pin
uptonryan19-Nov-06 20:46
memberuptonryan19-Nov-06 20:46 
GeneralRe: Win32 Application Pin
YaoTown11-Mar-08 18:08
memberYaoTown11-Mar-08 18:08 
QuestionRe: Win32 Application Pin
netlogging4-Apr-08 5:47
membernetlogging4-Apr-08 5:47 
QuestionProject Files? Pin
Uwe Komoss6-Aug-03 13:43
sussUwe Komoss6-Aug-03 13:43 
QuestionWhat is the keywords __gc ? Pin
gertano13-May-03 2:45
membergertano13-May-03 2:45 
AnswerRe: What is the keywords __gc ? Pin
Albert Pascual13-May-03 5:43
memberAlbert Pascual13-May-03 5:43 
GeneralRe: What is the keywords __gc ? Pin
gertano13-May-03 10:09
membergertano13-May-03 10:09 
GeneralRe: What is the keywords __gc ? Pin
Albert Pascual13-May-03 12:53
memberAlbert Pascual13-May-03 12:53 
AnswerRe: What is the keywords __gc ? Pin
wadegiles6-Jul-05 6:13
memberwadegiles6-Jul-05 6:13 
GeneralSerial comms sample code Pin
Colin Bowdery3-Apr-03 1:26
sussColin Bowdery3-Apr-03 1:26 
GeneralRe: Serial comms sample code Pin
wadegiles6-Jul-05 5:58
memberwadegiles6-Jul-05 5:58 
Generalusing this class with visual c++ Pin
SFH2-Apr-03 5:29
memberSFH2-Apr-03 5:29 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 17 Apr 2002
Article Copyright 2002 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid