Serial port program in c language
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Thread: Serial port program in c language

  1. #1
    Join Date
    Dec 2007
    Posts
    5

    Exclamation Serial port program in c language

    hi,
    this is chandu

    Right now i am working with serial port programming in c on visual studio environment

    i want to know about the program
    it should read the data on com port and write the data in com port
    it should include1) baud rate 2)comport selection 3) data that u wanted send


    if any can help out these things with code would be appreciated
    Thanks&Regards
    chandu

  2. #2
    Join Date
    Oct 2005
    Posts
    229

    Re: Serial port program in c language

    Hi chandu,

    First please dont double post your questions If you post in the wrong section a mod. will move it to the correct one.

    For serial port programming you use the ReadFile and WriteFile API functions.

    Check out the following links:
    DCB Settings
    Timeouts
    Reading serial port
    Writing serial port

    Communication functions

    Hope this helps
    Cheers
    Learning somthing new every day!

  3. #3
    Join Date
    Nov 2007
    Posts
    57

    Re: Serial port program in c language

    about com port selection..
    i have a piece of code attached.
    it works fine after compiled under dev-cpp in my computer.
    Attached Files Attached Files

  4. #4
    Join Date
    Nov 2007
    Posts
    57

    Re: Serial port program in c language

    And if you can only use windows APIs,you can try in this way.use CreateFile() to control the port.Following is the sourcecode. It opens the port, sets the Baud Rate,and you can use WriteFile() and ReadFile() functions to receive and send data.You can also search in MSDN for details.

    Code:
    #include <windows.h>
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
       DCB dcb;
       HANDLE hCom;
       BOOL fSuccess;
       char *pcCommPort = "COM2";
    
       hCom = CreateFile( pcCommPort,
                        GENERIC_READ | GENERIC_WRITE,
                        0,    // must be opened with exclusive-access
                        NULL, // no security attributes
                        OPEN_EXISTING, // must use OPEN_EXISTING
                        0,    // not overlapped I/O
                        NULL  // hTemplate must be NULL for comm devices
                        );
    
       if (hCom == INVALID_HANDLE_VALUE) 
       {
           // Handle the error.
           printf ("CreateFile failed with error %d.\n", GetLastError());
           return (1);
       }
    
       // Build on the current configuration, and skip setting the size
       // of the input and output buffers with SetupComm.
    
       fSuccess = GetCommState(hCom, &dcb);
    
       if (!fSuccess) 
       {
          // Handle the error.
          printf ("GetCommState failed with error %d.\n", GetLastError());
          return (2);
       }
    
       // Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.
    
       dcb.BaudRate = CBR_57600;     // set the baud rate
       dcb.ByteSize = 8;             // data size, xmit, and rcv
       dcb.Parity = NOPARITY;        // no parity bit
       dcb.StopBits = ONESTOPBIT;    // one stop bit
    
       fSuccess = SetCommState(hCom, &dcb);
    
       if (!fSuccess) 
       {
          // Handle the error.
          printf ("SetCommState failed with error %d.\n", GetLastError());
          return (3);
       }
    
       printf ("Serial port %s successfully reconfigured.\n", pcCommPort);
       return (0);
    }
    Last edited by jesschen; January 10th, 2008 at 02:36 PM.

  5. #5
    Join Date
    Jan 2008
    Posts
    3

    Re: Serial port program in c language

    i jesschen first of all thanx for your code.Now my problem sttement is tat i want to send char 'a' through the serial port in DevCpp windows.I modified your code and added some to do this,But it is not working can you please help me out?..

    The code

    #include <iostream>
    #include <conio.h>
    #include <stdio.h>
    #include <time.h>
    #include <windows.h>

    #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
    #include <bios.h>
    //#include <afxwin.h> // serial.cpp : Defines the entry point for the console application.

    //#include "stdafx.h"
    #include <string.h>
    #include "serial.h"

    // Flow control flags

    #define FC_DTRDSR 0x01
    #define FC_RTSCTS 0x02
    #define FC_XONXOFF 0x04

    // ascii definitions

    #define ASCII_BEL 0x07
    #define ASCII_BS 0x08
    #define ASCII_LF 0x0A
    #define ASCII_CR 0x0D
    #define ASCII_XON 0x11
    #define ASCII_XOFF 0x13
    using namespace std;
    // variables used with the com port
    BOOL bPortReady;
    DCB dcb;
    COMMTIMEOUTS CommTimeouts;
    BOOL bWriteRC;
    BOOL bReadRC;
    DWORD iBytesWritten;
    DWORD iBytesRead;

    void SerialPutc(HANDLE hCom, char txchar)
    {
    BOOL bWriteRC;
    static DWORD iBytesWritten;

    bWriteRC = WriteFile(hCom, &txchar, 1, &iBytesWritten,NULL);

    return;
    }
    int main(int argc, char *argv[])
    {
    DCB dcb;
    HANDLE hCom;
    //HANDLE *ptr;

    BOOL fSuccess;
    char *pcCommPort = "COM1";

    hCom = CreateFile( pcCommPort,
    GENERIC_READ | GENERIC_WRITE,
    0, // must be opened with exclusive-access
    NULL, // no security attributes
    OPEN_EXISTING, // must use OPEN_EXISTING
    0, // not overlapped I/O
    NULL // hTemplate must be NULL for comm devices
    );

    if (hCom == INVALID_HANDLE_VALUE)
    {
    // Handle the error.
    printf ("CreateFile failed with error %d.\n", GetLastError());
    return (1);
    }

    // Build on the current configuration, and skip setting the size
    // of the input and output buffers with SetupComm.

    fSuccess = GetCommState(hCom, &dcb);

    if (!fSuccess)
    {
    // Handle the error.
    printf ("GetCommState failed with error %d.\n", GetLastError());
    return (2);
    }

    // Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.

    dcb.BaudRate = CBR_9600; // set the baud rate
    dcb.ByteSize = 8; // data size, xmit, and rcv
    dcb.Parity = NOPARITY; // no parity bit
    dcb.StopBits = ONESTOPBIT; // one stop bit

    fSuccess = SetCommState(hCom, &dcb);

    if (!fSuccess)
    {
    // Handle the error.
    printf ("SetCommState failed with error %d.\n", GetLastError());
    return (3);
    }

    printf ("Serial port %s successfully reconfigured.\n", pcCommPort);
    //*ptr=hCom;
    for( ; ; )
    {

    SerialPutc(hCom,'a');
    //letter=SerialGetc(ptr);
    //cout<<letter<<endl;
    }
    getch();
    return (0);

    }
    Last edited by infibit; January 14th, 2008 at 04:05 AM.

  6. #6
    Join Date
    Feb 2005
    Location
    Pune (India)
    Posts
    644

    Thumbs up Re: Serial port program in c language

    Hi,

    What problem you are facing in this code ? and
    why you are sending data "a" in an infinite loop ? give some delay there

    i.e Sleep(500);


    plz use code tags while posting the code !

    -Anant
    "Devise the simplest possible solution that solves the problems"

  7. #7
    Join Date
    Nov 2010
    Posts
    105

    Question Re: Serial port program in c language

    Thank you for posting this info. I am trying to migrate from POSIX to Windows. I am dealing with USB-serial devices. For each read operation I need to know the number of bytes read. But I saw this in the ReadFile() manual page
    http://msdn.microsoft.com/en-us/libr...8VS.85%29.aspx
    ...
    lpNumberOfBytesRead [out, optional]

    A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile sets this value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.
    ...
    I believe serial port is asynchronous, but if I set the lpNumberOfBytesRead to NULL as recommended then how do I know the number of bytes read?

    Please help! Thanks!

    Also has anyone used 2,000,000 baud successfully?

  8. #8
    Join Date
    Feb 2002
    Posts
    4,640

    Re: Serial port program in c language

    In the "Remarks" section of the link you posted:
    If hFile was opened with FILE_FLAG_OVERLAPPED, the following conditions are in effect:

    * The lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, otherwise the function can incorrectly report that the read operation is complete.
    * The lpNumberOfBytesRead parameter should be set to NULL. Use the GetOverlappedResult function to get the actual number of bytes read. If the hFile parameter is associated with an I/O completion port, you can also get the number of bytes read by calling the GetQueuedCompletionStatus function.
    Viggy

  9. #9
    Join Date
    Jan 2009
    Posts
    54

    Re: Serial port program in c language

    A serial port is a very dumb device.
    You MUST know the protocol you intend to use between the communicating software components. In many cases you are 'talking' to another computing device (scanner, sensor etc.). They will have a clearly defined specification (down to the actual number of bytes and the meaning of the values) for the commands and allowed responses you may expect to receive.
    So. If the command to be sent is 'a' then SerialPutc(hcom, 'a') ONCE.
    The device should already be switched on and 'listening' on the serial port.
    It ought to respond to the 'a' command and send one of the EXPECTED responses.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center