CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jul 2010
    Posts
    1

    Open Serial Port using C

    I am using an AL5A Robotic arm. I would like to open the serial port using the C++ programming.

    My group partner and I have tried to look for a command to open the serial port. But in vain. We can do it in Matlab where we define and use the command serial to open the serial port as:

    S= serial('COM1', 'BaudRate', 115200);
    fopen(S);
    A=[35 48 80 49 49 53 55 84 48 48 48 13];
    fprintf(S, A);

    Those are the ASCII codes we need to send to the Servo motors of the robotic arm.

    I was wondering if there's a similar way of doing it in C++? If so, how? and what header files do we need? Please let me know.

    Thanks.

  2. #2
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: Open Serial Port using C

    Assuming you're talking about using COM port on Windows.
    Code:
    HANDLE hCom = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE/* as needed */, 0 /*must be exclusive*/, NULL, OPEN_EXISTING /* has to be this value */, 0, NULL);
    
    DCB dcb;
    ZeroMemory(&dcb, sizeof(dcb));
    dcb.DCBlength = sizeof(DCB);
    if ( GetCommState(hCom, &dcb) )
    {
       // Set as needed
       dcb.BaudRate = CBR_57600;     
       dcb.ByteSize = 8;      
       dcb.Parity = NOPARITY;
       dcb.StopBits = ONESTOPBIT;
    
       SetCommState(hCom, &dcb);
    }
    you can then use ReadFile/WriteFile to read/write to the com port.

    Don't forget to close the handle or the com port might be locked from further use.


    Error handling has been left out of the above example to keep it short.

Tags for this Thread

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured