Reading from serial port using VC++

C, C++, Visual C++, C++.Net Topics
Post Reply
User avatar
SevenZero
Major
Major
Posts: 263
Joined: Sun Nov 01, 2009 8:37 pm

Reading from serial port using VC++

Post by SevenZero » Fri Feb 11, 2011 12:01 am

Here is how you could read from the serial port using Visual C++.

Code: Select all

#include <windows.h>
#include <stdio.h>





int main(int argc, char **argv)
{

	unsigned char szBuffer[1];
	DCB dcb = {0};
	DWORD dwRead;
	HANDLE hComm;
	OVERLAPPED ovlr = {0};
	COMMTIMEOUTS cto;


	// Create events for overlapped operation
	ovlr.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);


	// Open the port
	hComm = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE,	0, NULL, OPEN_EXISTING,	FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);


	// Get the state of the device and modify it
	dcb.DCBlength = sizeof(dcb);
	
	GetCommState(hComm, &dcb);

	dcb.BaudRate = CBR_115200;
	dcb.StopBits = ONESTOPBIT;
	dcb.ByteSize = 8;
	dcb.Parity   = NOPARITY;
	dcb.fParity  = FALSE;

	SetCommState(hComm, &dcb);


	// Set the timeout parameters nonsensically
	cto.ReadIntervalTimeout = 1000;
	cto.ReadTotalTimeoutConstant = 1000;
	cto.ReadTotalTimeoutMultiplier = 1000;
	cto.WriteTotalTimeoutConstant = 1000;
	cto.WriteTotalTimeoutMultiplier = 1000;

	SetCommTimeouts(hComm, &cto);



	while (1){
		ReadFile (hComm, szBuffer, sizeof(szBuffer), &dwRead, &ovlr);

		if ( GetOverlappedResult(hComm, &ovlr, &dwRead, TRUE) )
		{
			// Process data in szBuffer buffer
		}
	}


	// Close the device
	CloseHandle(hComm);


	return 0;
}
User avatar
Enigma
Lieutenant
Lieutenant
Posts: 74
Joined: Sun Jan 16, 2011 12:40 am
Location: Colombo, Sri Lanka

Re: Reading from serial port using VC++

Post by Enigma » Fri Feb 11, 2011 6:20 pm

nice.
Here is the MSDN article for serial communication
http://msdn.microsoft.com/en-us/library/ms810467
:mrgreen:
Post Reply

Return to “C/C++ Programming”