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);
}
----
|