?
Solved

Serial Port Communications in Visual C++

Posted on 2003-03-24
3
Medium Priority
?
447 Views
Last Modified: 2008-03-17
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(
                         m_sComPort,
                         GENERIC_READ | GENERIC_WRITE,
                         0,                                        // exclusive access
                         NULL,                                   // no security
                         OPEN_EXISTING,
                         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);
                   
MessageBox(NULL,Input,"Testing...",MB_YESNO);


Thats the code I've got at the moment, but I sort of just butchered the routines from somewhere else. can anyone help?
0
Comment
Question by:gb115
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 

Accepted Solution

by:
DidierT earned 200 total points
ID: 8196772
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() ;
           break;
        case WAIT_OBJECT_0 :       // killed !
           break;
        case WAIT_IO_COMPLETION : // Read completed
            nbBytes = (unsigned long)overlapped.hEvent ;
            break ;
      }
   }
   else
   {
      // .... 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 ;
   }
   else
   {
      SetLastError(dwErrorCode);
   }
}


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).

Did

0
 
LVL 11

Expert Comment

by:bcladd
ID: 9558713
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.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

-bcl (bcladd)
EE Cleanup Volunteer
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses
Course of the Month8 days, 3 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question