#include <stdio.h>
#include <windows.h>
BOOL fSuccess;
HANDLE hSerial; //Handle for COM Port
void initComm()
{
COMMTIMEOUTS noblock;
DCB comSettings; //Various Port Settings
// Initialize Serial Port
hSerial = CreateFile("COM1", //Open COM1
GENERIC_READ, //Read only
0, //Exclusive Access
NULL, //No Security Attributes
OPEN_EXISTING, //COM port already exists
0,
NULL);
if (hSerial==INVALID_HANDLE_VALUE)
{
printf("Invalid Handle Value %d.\n", GetLastError());
}
//Set TimeOut in Milisecs
fSuccess = GetCommTimeouts(hSerial, &noblock);
noblock.ReadTotalTimeoutConstant = 1;
noblock.ReadTotalTimeoutMultiplier = MAXWORD;
noblock.ReadIntervalTimeout = MAXWORD;
fSuccess = SetCommTimeouts(hSerial, &noblock);
//Set Port Parameters
fSuccess = GetCommState(hSerial, &comSettings);
if(!fSuccess)
{
printf("\nGetCommState Error!");
}
comSettings.BaudRate = 9600;
comSettings.ByteSize = 8;
comSettings.fParity = FALSE;
comSettings.Parity = NOPARITY;
comSettings.StopBits = ONESTOPBIT;
fSuccess = SetCommState(hSerial, &comSettings);
if(!fSuccess){
printf("\nSetCommState Error!");
}
printf("Comm port set\n");
}
//Read Data from Serial Port
char readComm()
{
char inBuffer;
int bytesRead;
fSuccess = ReadFile(hSerial, //Handle
&inBuffer, //Incoming data
1000, //No bytes to read
&bytesRead, //Bytes Read
0);
if (bytesRead >0)
return inBuffer;
else return 0;
}
|