1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <time.h>
int openPort(HANDLE *h)
{
DCB dcb = {0};
COMMTIMEOUTS timeouts={0};
BOOL portReady,fSuccess;
int retValue;
retValue = 0;
*h = CreateFile(
"\\\\.\\COM40",
GENERIC_READ,
0, // must be opened with exclusive-access
NULL, // default security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
0, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
if(*h == INVALID_HANDLE_VALUE)
{ // Handle the error.
printf ("CreateFile failed with error %d.\n", GetLastError());
retValue = 1;
}
// define buffer size for sending and receiving [number of Bytes]
portReady = SetupComm(*h,1024,1024);
if (!portReady)
{ // Handle the error.
printf ("SetupComm failed with error %d.\n", GetLastError());
retValue = 2;
}
// define state of commport
fSuccess = GetCommState(*h, &dcb);
if (!fSuccess)
{ // Handle the error.
printf ("GetCommState failed with error %d.\n", GetLastError());
retValue = 3;
}
// Fill in DCB: 9,600 bps, 8 data bits, no parity, and 1 stop bit.
dcb.BaudRate = CBR_9600; // set the baud rate
dcb.ByteSize = 8; // data size
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
fSuccess = SetCommState(*h, &dcb);
if (!fSuccess)
{ // Handle the error.
printf ("SetCommState failed with error %d.\n", GetLastError());
retValue = 4;
}
// define Timeouts [milliseconds]
timeouts.ReadIntervalTimeout=10;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.ReadTotalTimeoutConstant=1000;
fSuccess = SetCommTimeouts(*h,&timeouts);
if(!fSuccess)
{
printf ("SetCommTimeouts failed with error %d.\n", GetLastError());
retValue = 5;
}
return retValue;
} |
Partager