为什么串口无法正常开启?
有如下程序,为MSDN中的示例代码,可是为什么运行时显示:
GetCommState failed with error 2, msdn中说明为:
2 (ERROR_FILE_NOT_FOUND) : The system cannot find the file specified
可是我的电脑有串口呀,把"COM1"改为"COM2"也不行,代码如下:
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
DCB dcb;
HANDLE hCom;
BOOL fSuccess;
TCHAR *pcCommPort = TEXT("COM1");
hCom = CreateFile( "COM1",
GENERIC_READ | GENERIC_WRITE,
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 (hCom == INVALID_HANDLE_VALUE)
{
// Handle the error.
printf ("CreateFile failed with error %d.\n", GetLastError());
return (1);
}
// Build on the current configuration, and skip setting the size
// of the input and output buffers with SetupComm.
// SecureZeroMemory(&dcb, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
printf ("GetCommState failed with error %d.\n", GetLastError());
return (2);
}
// Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.
dcb.BaudRate = CBR_57600; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
fSuccess = SetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
printf ("SetCommState failed with error %d.\n", GetLastError());
return (3);
}
_tprintf (TEXT("Serial port %s successfully reconfigured.\n"), pcCommPort);
return (0);
}