Thread: Serial Port Communication

  1. #1
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318

    Serial Port Communication

    Is there any way to use serial port communication with Dev-C++?
    I searched about it from google but found nothing that would work or what libraries i have. Can anyone suggest at least ONE working example of a serial port communication?

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    For MS-Windows os you can use win32 api functions -- use CreateFile() to open the com port. Read about that function in MSDN and it will give you links to other functions you will need. When you get to that function in MSDN, scroll down to near the bottom where it discusses serial communications.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Well life begins with CreateFile() for win32 programming

    Or perhaps
    http://www.lvr.com/serport.htm
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715
    It would be very good if someone place a simple code that demonstrate serial port communication (win 32). Perhaps the FAQ would be a good place.
    Gotta love the "please fix this for me, but I'm not going to tell you which functions we're allowed to use" posts.
    It's like teaching people to walk by first breaking their legs - muppet teachers! - Salem

  5. #5
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    See This sample

  6. #6
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    I need C++ Win32 example that would run on Windows XP and compile with Dev-C++. .net framework isn't what I'm looking for.
    This isn't in C++ and is not using Win32 and can't be compiled with Dev-C++.

    I found a little example connecting to adr2000 (i don't know what it is). Can anyone modify it so it would receive normal data?
    Last edited by maxorator; 04-26-2006 at 07:26 AM.

  7. #7
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    I have a little code... How can I open a normal port? (this doesnt work)
    Code:
    #include <windows.h>
    #include <string>
    #define READ_BUF_SIZE 4096
    BOOL     m_bPortReady;
    HANDLE   m_hCom;
    char  m_sComPort[256]={'\\','\\','.','\\','C','O','M','1','8','7','9'};
    DCB      m_dcb;
    HWND hwnd;
    COMMTIMEOUTS m_CommTimeouts;
    BOOL     bWriteRC;
    BOOL     bReadRC;
    DWORD iBytesWritten;
    DWORD iBytesRead;
    DWORD dwRead;
    BOOL fWaitingOnRead = FALSE;
    OVERLAPPED osReader = {0};
    void HandleASuccessfulRead(char* lpBuf, DWORD dwRead);
    char       sBuffer[128];
    /*  Declare Windows procedure  */
    LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
    
    /*  Make the class name into a global variable  */
    char szClassName[ ] = "WindowsApp";
    
    int WINAPI WinMain (HINSTANCE hThisInstance,
                        HINSTANCE hPrevInstance,
                        LPSTR lpszArgument,
                        int nFunsterStil)
    
    {
        MSG messages;            /* Here messages to the application are saved */
        WNDCLASSEX wincl;        /* Data structure for the windowclass */
    
        /* The Window structure */
        wincl.hInstance = hThisInstance;
        wincl.lpszClassName = szClassName;
        wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
        wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
        wincl.cbSize = sizeof (WNDCLASSEX);
    
        /* Use default icon and mouse-pointer */
        wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
        wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
        wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
        wincl.lpszMenuName = NULL;                 /* No menu */
        wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
        wincl.cbWndExtra = 0;                      /* structure or the window instance */
        /* Use Windows's default color as the background of the window */
        wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
    
        /* Register the window class, and if it fails quit the program */
        if (!RegisterClassEx (&wincl))
            return 0;
    
        /* The class is registered, let's create the program*/
        hwnd = CreateWindowEx (
               0,                   /* Extended possibilites for variation */
               szClassName,         /* Classname */
               "Windows App",       /* Title Text */
               WS_OVERLAPPEDWINDOW, /* default window */
               CW_USEDEFAULT,       /* Windows decides the position */
               CW_USEDEFAULT,       /* where the window ends up on the screen */
               544,                 /* The programs width */
               375,                 /* and height in pixels */
               HWND_DESKTOP,        /* The window is a child-window to desktop */
               NULL,                /* No menu */
               hThisInstance,       /* Program Instance handler */
               NULL                 /* No Window Creation data */
               );
    
        /* Make the window visible on the screen */
        ShowWindow (hwnd, nFunsterStil);
    
        /* Run the message loop. It will run until GetMessage() returns 0 */
        while (GetMessage (&messages, NULL, 0, 0))
        {
            /* Translate virtual-key messages into character messages */
            TranslateMessage(&messages);
            /* Send message to WindowProcedure */
            DispatchMessage(&messages);
        }
    
        /* The program return-value is 0 - The value that PostQuitMessage() gave */
        return messages.wParam;
    }
    
    
    /*  This function is called by the Windows function DispatchMessage()  */
    
    LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
        switch (message)                  /* handle the messages */
        {
            case WM_CREATE:
                m_hCom=CreateFile("5789",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
                if(m_hCom!=INVALID_HANDLE_VALUE){
                m_bPortReady=SetupComm(m_hCom,128,128);
                m_bPortReady=GetCommState(m_hCom,&m_dcb);
                m_dcb.BaudRate = 9600;
                m_dcb.ByteSize = 8;
                m_dcb.Parity = NOPARITY;
                m_dcb.StopBits = ONESTOPBIT;
                m_dcb.fAbortOnError = TRUE;
                m_bPortReady=SetCommState(m_hCom,&m_dcb);
                m_bPortReady = GetCommTimeouts (m_hCom, &m_CommTimeouts);
                m_CommTimeouts.ReadIntervalTimeout = 50;
                m_CommTimeouts.ReadTotalTimeoutConstant = 50;
                m_CommTimeouts.ReadTotalTimeoutMultiplier = 10;
                m_CommTimeouts.WriteTotalTimeoutConstant = 50;
                m_CommTimeouts.WriteTotalTimeoutMultiplier = 10;
    if (!fWaitingOnRead) {
       // Issue read operation.
       if (!ReadFile(m_hCom, sBuffer, READ_BUF_SIZE, &dwRead, &osReader)) {
          if (GetLastError() != ERROR_IO_PENDING){MessageBox(hwnd,"error","error",MB_OK);}     // read not delayed?
              
             // Error in communications; report it.
          else{
             fWaitingOnRead = TRUE;}
       }
       else {    
          // read completed immediately
          HandleASuccessfulRead(sBuffer, dwRead);
        }
    }
                MessageBox(hwnd,sBuffer,sBuffer,MB_OK);
                }
                break;
            case WM_DESTROY:
                PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
                CloseHandle(m_hCom);
                break;
            default:                      /* for messages that we don't deal with */
                return DefWindowProc (hwnd, message, wParam, lParam);
        }
    
        return 0;
    }
    void HandleASuccessfulRead(char* lpBuf, DWORD dwRead){
       MessageBox(hwnd,lpBuf,lpBuf,MB_OK);
    }

  8. #8
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    Quote Originally Posted by maxorator
    I need C++ Win32 example that would run on Windows XP and compile with Dev-C++. .net framework isn't what I'm looking for.
    This isn't in C++ and is not using Win32 and can't be compiled with Dev-C++.

    I found a little example connecting to adr2000 (i don't know what it is). Can anyone modify it so it would receive normal data?

    who don't you learn to use google if you don't like my example? There are millions of example floating around if only you would bother to hunt for them.

  9. #9
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    There is nothing wrong about your example, it's just not what I'm looking for.
    And I've searched from google for hours, but there is no working example in the first... 10 pages.

  10. #10
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    http://www.codeproject.com/system/SerialPortComm.asp
    This is a serial port connection code, but how can I specify a port to be opened (I mean a port like "1502" or some other number)?
    I've seen no example that shows how to open a port...

    Edit:
    Thanks to the people who tried to help. I found this code using WinSock:
    Code:
    #include <stdio.h>
    #include "winsock2.h"
    
    int main(){
    // Initialize Winsock.
        WSADATA wsaData;
        int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
        if ( iResult != NO_ERROR )
            printf("Error at WSAStartup()\n");
    
        // Create a socket.
        SOCKET m_socket;
        m_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
    
        if ( m_socket == INVALID_SOCKET ) {
            printf( "Error at socket(): %ld\n", WSAGetLastError() );
            WSACleanup();
            return 0;
        }
    
        // Bind the socket.
        sockaddr_in service;
    
        service.sin_family = AF_INET;
        service.sin_addr.s_addr = inet_addr( "127.153.148.70" );
        service.sin_port = htons( 27015 );
    
        if ( bind( m_socket, (SOCKADDR*) &service, sizeof(service) ) == SOCKET_ERROR ) {
            printf( "bind() failed.\n" );
            closesocket(m_socket);
            return 0;
        }
        
        // Listen on the socket.
        if ( listen( m_socket, 1 ) == SOCKET_ERROR )
            printf( "Error listening on socket.\n");
    
        // Accept connections.
        SOCKET AcceptSocket;
    
        printf( "Waiting for a client to connect...\n" );
        while (1) {
            AcceptSocket = SOCKET_ERROR;
            while ( AcceptSocket == SOCKET_ERROR ) {
                AcceptSocket = accept( m_socket, NULL, NULL );
            }
            printf( "Client Connected.\n");
            m_socket = AcceptSocket; 
            break;
        }
        
        // Send and receive data.
        int bytesSent;
        int bytesRecv = SOCKET_ERROR;
        char sendbuf[32] = "Server: Sending Data.";
        char recvbuf[32] = "";
        
        bytesRecv = recv( m_socket, recvbuf, 32, 0 );
        printf( "Bytes Recv: %ld\n", bytesRecv );
        
        bytesSent = send( m_socket, sendbuf, strlen(sendbuf), 0 );
        printf( "Bytes Sent: %ld\n", bytesSent );
    
        WSACleanup();
    
        return 0;
    }
    Last edited by maxorator; 04-27-2006 at 11:00 AM.

  11. #11
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    you cannot specify the port number. It must be something like "COM1:", "COM2:" etc. MS-Windows operating system (and *nix too) will not permit you to access hardware directly, like old MS-DOS did.
    Last edited by Ancient Dragon; 04-27-2006 at 11:19 AM.

  12. #12
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    I think you're a little off track with the latest code. It's network code as in client/server applications. It isn't exactly serial communications code. So, I've included a code snippet that I use to communicate via a serial port with a security controller.

    Code:
    #include <windows.h>
    #include <stdio.h>
    #include <string.h>
    
    HANDLE hPort;
    
    BOOL WriteByte(BYTE bybyte)
    {
        DWORD iBytesWritten=0;
        DWORD iBytesToRead = 1;
        if(WriteFile(hPort,(LPCVOID) 
            &bybyte,iBytesToRead,&iBytesWritten,NULL)==0)
            return FALSE;
        else return TRUE;
    }
    
    BOOL WriteString(const void *instring, int length)
    {
        int index;
        BYTE *inbyte = (BYTE *) instring;
        for(index = 0; index< length; ++index)
        {
            if (WriteByte(inbyte[index]) == FALSE)
                return FALSE;
        }
        return TRUE;
    }
    
    BOOL ReadByte(BYTE  &resp)
    {
        BOOL bReturn = TRUE;
        BYTE rx;
        DWORD dwBytesTransferred=0;
    
        if (ReadFile (hPort, &rx, 1, &dwBytesTransferred, 0)> 0)
        {
            if (dwBytesTransferred == 1)
            {
                resp=rx;
                bReturn  = TRUE;
            }
            else bReturn = FALSE;
        }
        else    bReturn = FALSE;
        return bReturn;
    }
    
    BOOL ReadString(void *outstring, int *length)
    {
        BYTE data;
        BYTE dataout[4096]={0};
        int index = 0;
        while(ReadByte(data)== TRUE)
        {
            dataout[index++] = data;
        }
        memcpy(outstring, dataout, index);
        *length = index;
        return TRUE;
    }
    
    void ClosePort()
    {
        CloseHandle(hPort);
        return;
    }
    
    HANDLE ConfigureSerialPort(LPCSTR  lpszPortName)
    {
        HANDLE hComm = NULL;
        DWORD dwError;
        DCB PortDCB;
        COMMTIMEOUTS CommTimeouts;
        // Open the serial port.
        hComm = CreateFile (lpszPortName, // Pointer to the name of the port
            GENERIC_READ | GENERIC_WRITE,
            // Access (read-write) mode
            0,              // Share mode
            NULL,           // Pointer to the security attribute
            OPEN_EXISTING,  // How to open the serial port
            0,              // Port attributes
            NULL);          // Handle to port with attribute
        // to copy
    
        // Initialize the DCBlength member.
        PortDCB.DCBlength = sizeof (DCB);
        // Get the default port setting information.
        GetCommState (hComm, &PortDCB);
        // Change the DCB structure settings.
        PortDCB.BaudRate = 9600;              // Current baud
        PortDCB.fBinary = TRUE;               // Binary mode; no EOF check
        PortDCB.fParity = TRUE;               // Enable parity checking
        PortDCB.fOutxCtsFlow = FALSE;         // No CTS output flow control
        PortDCB.fOutxDsrFlow = FALSE;         // No DSR output flow control
        PortDCB.fDtrControl = DTR_CONTROL_ENABLE;
        // DTR flow control type
        PortDCB.fDsrSensitivity = FALSE;      // DSR sensitivity
        PortDCB.fTXContinueOnXoff = TRUE;     // XOFF continues Tx
        PortDCB.fOutX = FALSE;                // No XON/XOFF out flow control
        PortDCB.fInX = FALSE;                 // No XON/XOFF in flow control
        PortDCB.fErrorChar = FALSE;           // Disable error replacement
        PortDCB.fNull = FALSE;                // Disable null stripping
        PortDCB.fRtsControl = RTS_CONTROL_ENABLE;
        // RTS flow control
        PortDCB.fAbortOnError = FALSE;        // Do not abort reads/writes on
        // error
        PortDCB.ByteSize = 8;                 // Number of bits/byte, 4-8
        PortDCB.Parity = NOPARITY;            // 0-4=no,odd,even,mark,space
        PortDCB.StopBits = ONESTOPBIT;        // 0,1,2 = 1, 1.5, 2
    
        // Configure the port according to the specifications of the DCB
        // structure.
        if (!SetCommState (hComm, &PortDCB))
        {
            printf("Could not configure serial port\n");
            return NULL;
        }
        // Retrieve the time-out parameters for all read and write operations
        // on the port.
        GetCommTimeouts (hComm, &CommTimeouts);
        // Change the COMMTIMEOUTS structure settings.
        CommTimeouts.ReadIntervalTimeout = MAXDWORD;
        CommTimeouts.ReadTotalTimeoutMultiplier = 0;
        CommTimeouts.ReadTotalTimeoutConstant = 0;
        CommTimeouts.WriteTotalTimeoutMultiplier = 0;
        CommTimeouts.WriteTotalTimeoutConstant = 0;
        if (!SetCommTimeouts (hComm, &CommTimeouts))
        {
            printf("Could not set timeouts\n");
            return NULL;
        }
        return hComm;
    }
    
    int main(void)
    {
        //  Can also use COM2, COM3 or COM4 here
        hPort = ConfigureSerialPort("COM1");
        if(hPort == NULL)
        {
            printf("Com port configuration failed\n");
            return -1;
        }
        // Call your ReadString and WriteString functions here
        ClosePort();
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Duplex communication thro serial port
    By Priyachu in forum Networking/Device Communication
    Replies: 1
    Last Post: 05-30-2009, 04:24 AM
  2. Duplex communication thro serial port
    By Priyachu in forum Linux Programming
    Replies: 1
    Last Post: 05-30-2009, 04:03 AM
  3. Serial port Communication
    By vin_pll in forum C++ Programming
    Replies: 23
    Last Post: 01-07-2009, 09:32 AM
  4. DOS, Serial, and Touch Screen
    By jon_nc17 in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 01-08-2003, 04:59 PM
  5. Need help or info about serial port communication
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 01-08-2002, 01:48 PM