David J. Barnes

567 W 18th Street
Chicago, Il 60616 U.S.A.
+1 (312) 351-52849
Hello@DavidJBarnes.com
David J Barnes | Software Engineer Welcome
Current Projects
Publicly Available Software
Research Interests
Tutorials and Code Examples
Professional Experience
Charity & Volunteer Work
On Robotics and Mechatronics

Tutorials and Code Examples


Back to all Tutorials and Code Examples

Serial Port Programming in C++

Below is a simple method for communicating with a PCs serial port. You can leverage the Windows API to connect to an available com port. The WritePort(param1, param2, param3, param4) takes four parameters and returns a bool(retVal) describing the sucess of the call.

Download the .cpp file.

#include <iostream>
#include <windows.h>
#include <commctrl.h>
#include <iostream>

using namespace std;

void WritePort(void);

int main()
{
    WritePort();

    return 0;
}

void WritePort(void)
{
    DCB dcb;
    DWORD BytesWritten;

    HANDLE hPort = CreateFile(
                    "\\\\.\\COM21",
                    GENERIC_WRITE,
                    0,
                    NULL,
                    OPEN_EXISTING,
                    0,
                    NULL
    );

    dcb.BaudRate = CBR_4800;
    dcb.ByteSize = 8;
    dcb.Parity = NOPARITY;
    dcb.StopBits = ONESTOPBIT;

    bool retVal = WriteFile(hPort,"79\n",1,&BytesWritten,NULL);

    CloseHandle(hPort);
}

----