How to Read & Write the COM Port - A Step by Step Approach
CoderSource.net
How to Read & Write the COM Port - A Step by Step Approach - Article by bagavathikumar
Level: BeginnerType: Article
Rating: 3Page: 3 of 3

Date: 2/3/2006 12:00:00 AM

Environment: Windows, VC, VC.NET

Step 9: Add a Method called BOOL ConfigureCOMPort(int nPortNo)

   1.

Goto the Class View and select the CReadCOMView class.
   2. Right click the CReadCOMView in ClassView and select add -> add Function.
   3. Enter the method name and parameters.
   4. Add the following code to that method.

    CString strPort;
    BOOL fSuccess;
    COMMTIMEOUTS timeout;
    DCB dcb;

    strPort.Format("COM%d", nPortNo) ;

    //Create the handle for read the COM port
    m_hFile =  CreateFile( strPort,
                    GENERIC_READ | GENERIC_WRITE,
                    (DWORD)NULL,   // exclusive access
                    NULL,          // no security
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL,
                    NULL           // hTemplate
                    );

    //Check weather the handle is valid or not
    if (INVALID_HANDLE_VALUE == m_hFile)
    {
        AfxMessageBox("Error: Could not open the RS232 port!", MB_OK|MB_ICONEXCLAMATION);
        return FALSE;
    }


    // set up the comms parameters now that we have a handle
    SetupComm(m_hFile,(DWORD)2048, (DWORD)2048);


    // Set up the DCB with our settings
    // Get it first so we fill all members
    fSuccess = GetCommState(m_hFile,&dcb);

    if (!fSuccess)
    {
        // Handle the error.
        AfxMessageBox ("Error: Failed to Get the System Communication Settings.", MB_OK|MB_ICONEXCLAMATION );
                return FALSE;
    }

    dcb.BaudRate = CBR_9600;
    dcb.ByteSize = 8;            // data size
    dcb.Parity = NOPARITY;        // No Parity Bit
    dcb.StopBits = ONESTOPBIT;

    // assign it
    fSuccess = SetCommState(m_hFile, &dcb);

    //Now check the configuration of the communication device is valid or
    //not after assign the comms parameters
    if ( fSuccess == 0 )
    {
        AfxMessageBox("Error: In Control Setting for a Serial Communications Device.", MB_OK|MB_ICONEXCLAMATION);
        return FALSE;
    }

    // Set up the timeouts to use, they are quite short, since we will loop anyway.
    // Do not make them zero, else we will have a CPU load problem. Too large a value,
    // and we have to wait for comms to time out when shutting down

    // fill timeout structure
    GetCommTimeouts(m_hFile, &timeout);
    timeout.ReadIntervalTimeout = 100;           // 500ms between incomming chars.
    timeout.ReadTotalTimeoutConstant = 500;
    timeout.ReadTotalTimeoutMultiplier = 0;
    timeout.WriteTotalTimeoutConstant = 2000;
    timeout.WriteTotalTimeoutMultiplier = 60;    // 60ms per char sent

    SetCommTimeouts(m_hFile, &timeout);

    return TRUE;


Step 10: Add the OnTimer Message

   1. Go to solution explorer and double click the ReadCOM file.
   2. Go to Properties window and select Messages icon.
   3. Select the WM_TIMER Message and Add the OnTimer Event.
   4. Add the following code.

    unsigned char set_Data[15];

    // Prepare the Dummy Data for read and write the COM Port.
    for(int c=0; c<10; c++)
            set_Data[c] = 65 + c;

    // Write the Data to COM Port
    WriteToCOMPort(set_Data);

    unsigned char get_Data[15];

    ReadFromCOMPort(get_Data);

    m_txtRead.SetWindowText( (LPCTSTR)get_Data );
    CFormView::OnTimer(nIDEvent);


Step 11: Add the ReadFromCOMPort(unsigned char* c_Data) method.

BOOL CReadCOMView::ReadFromCOMPort(unsigned char* c_Data)
{
    BOOL error;

    DWORD numberOfBytesRead = 0;
    error = ReadFile(m_hFile,
                c_Data,
                10,                 // Number Of Bytes To                 Read,
                &numberOfBytesRead,
                NULL);

    if(numberOfBytesRead == 0)
        return FALSE;

    c_Data[numberOfBytesRead] = '\0' ;
    SetDlgItemText(LBL_VIS_SLABEL, (LPCTSTR)c_Data);

    return TRUE;
}


Step 12: Add the WriteToCOMPort(unsigned char* c_Data) method.

BOOL CReadCOMView::WriteToCOMPort(unsigned char* c_Data)
{
    BOOL fSuccess;
    DWORD numberOfBytesWritten=0;

    // send the bytes out on the wire
    if (INVALID_HANDLE_VALUE == m_hFile)
    {
        MessageBox("Error: Cannot send. Port closed!\n");   // busy shutting down the app
        return FALSE;
    }

    fSuccess = WriteFile(m_hFile,
                c_Data,
                10,                 //  Number Of Bytes To                     Write,
                &numberOfBytesWritten,
                NULL);
    return TRUE;

    if(!fSuccess)
    {
        AfxMessageBox("Error: Could not Write the data to RS232 port!", MB_OK|MB_ICONEXCLAMATION);
        return FALSE;
    }
    return TRUE;
}


Now run the program. it will read & write the COM port. The out put of the program is ABCDEFGHIJ.

Attachments

Source Files Sample Program

1 2 3

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us