• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 468
  • Last Modified:

Serial Port Communications in Visual C++

hi, I've been writing an app to try and communicate with a device over the com ports, I've managed to open the port and send information to the device, but I can't work out how to recieve information from the devices.  I need to write code that waits for some input, then recieves it and acts upon it.  I think I need to use somethign liek waitforcommevent (or something like that) but I'm not sure how it works.

// create com port
m_sComPort = "COM3:";
m_hCom = CreateFile(
                         GENERIC_READ | GENERIC_WRITE,
                         0,                                        // exclusive access
                         NULL,                                   // no security
                         0,                                        // no overlapped I/O
                         NULL);                                   // null template

// configure serial port
m_bPortReady = GetCommState(m_hCom, &m_dcb);
m_dcb.BaudRate = 112500;
m_dcb.ByteSize = 8;
m_dcb.Parity = NOPARITY;
m_dcb.StopBits = ONESTOPBIT;
m_dcb.fAbortOnError = TRUE;
m_bPortReady = SetCommState(m_hCom, &m_dcb);

// Enable PC Control
bWriteRC = WriteFile(m_hCom, "AT*EAM=\"PC\"\r",12,&iBytesWritten,NULL);

// Wait for input

BYTE  Byte;
DWORD dwCommModemStatus, dwBytesTransferred;
CString Input = "";

SetCommMask (m_hCom, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING);

WaitCommEvent (m_hCom, &dwCommModemStatus, 0);

do {
// Read the data from the serial port.

ReadFile (m_hCom, &Byte, 1, &dwBytesTransferred, 0);

// Display the data read.

if (dwBytesTransferred == 1)
{Input += Byte;}
} while (dwBytesTransferred == 1);

Thats the code I've got at the moment, but I sort of just butchered the routines from somewhere else. can anyone help?
1 Solution
Hi !

You must use IO_COMPLETION in a WaitForMultipleObjectFunction. Here is a short code :

int MySerPort::read()
   OVERLAPPED  overlapped  ;
   int         waitReport  ;
   int         res , nbBytesRead ;
   // Read completion structure
   overlapped.Offset = 0;
   overlapped.OffsetHigh = 0;
   overlapped.hEvent = NULL;// Filled w nb of bytes read
   // Read on the port
   // give Completion routine "OnReceive"
   res = ReadFileEx( m_hComm, buffer, size,
                     &overlapped, onReceive) ;
   // Wait for completion (Infinite !)
   if ( res )
      waitReport = WaitForSingleObjectEx(
                      m_killWaitingData ,
                      INFINITE          ,
                      true              ) ;// wait flag
      // Completion test
      switch (waitReport)
        case -1 :     // kill
        err = GetLastError() ;
        case WAIT_OBJECT_0 :       // killed !
        case WAIT_IO_COMPLETION : // Read completed
            nbBytes = (unsigned long)overlapped.hEvent ;
            break ;
      // .... Something wrong !
   return ( nbBytes ) ;

Create a completion CallBack routine as follow :

static void CALLBACK onReceive(  DWORD dwErrorCode      ,
                                 DWORD dwNbOfBytesTransf,
                                 LPOVERLAPPED lpOverlp      )
   if (dwErrorCode == NO_ERROR)
      // Set the number of bytes received
      lpOverlp->hEvent = (HANDLE)dwNbOfBytesTransf ;

When read is completed, the callback routine is called and then your process exit the waitForMultipleObject wait.

You can also do as well with a time-out different from INFINITE. The m_killWaitingData event is used to unblock your reception thread if necessary (on destructor for example).


No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Answered: Points to DidierT

Please leave any comments here within the next seven days. Experts: Silence
means you don't care.


-bcl (bcladd)
EE Cleanup Volunteer
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now