这是我的代码。err一直是2
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE HandlePort = CreateFile(L"COM5", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (HandlePort == INVALID_HANDLE_VALUE)
{
printf("串口打开失败\n");
int err = GetLastError();
printf("%d", err);
}
while (true);
return 0;
}
错误2是‘系统找不到指定的文件’,你有com5 吗,确认名字是否正确
COM1-COM9都试过了,都不行
CreateFile(
"////.//COM5", // address of name of the communications device
fdwAccess, // access (read-write) mode
0, // share mode
NULL, // address of security descriptor
OPEN_EXISTING, // how to create
0, // file attributes
NULL // handle of file with attributes to copy
);
把OPEN_EXISTING后边的0,改成FILE_FLAG_OVERLAPPED试试。
// get a handle to the port
m_hComm = CreateFile(szPort, // communication port string (COMX)
GENERIC_READ | GENERIC_WRITE, // read/write types
0, // comm devices must be opened with exclusive access
NULL, // no security attributes
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
FILE_FLAG_OVERLAPPED, // Async I/O
0); // template must be 0 for comm devices
if (m_hComm == INVALID_HANDLE_VALUE)
{
DWORD dwrst=GetLastError();
// port not found
delete [] szPort;
delete [] szBaud;
return FALSE;
}
// get a handle to the port
m_hComm = CreateFile("\\\\.\\COM1", // communication port string (COMX)
GENERIC_READ | GENERIC_WRITE, // read/write types
0, // comm devices must be opened with exclusive access
NULL, // no security attributes
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
FILE_FLAG_OVERLAPPED, // Async I/O
0);
改成这样应该可以吧。这个是我用的一个代码片段,你测试看看。
建议你先用标准的串口调试工具试一下有哪几个串口可用吧,可能真不是程序的问题。
额,没有弄过串口,但我弄过物理磁盘读写,打开磁盘设备就需要管理员权限,所以我想有没有可能是因为操作串口也需要管理员权限呢,使用管理员权限运行你的程序再试一下。你的代码应该没问题,祝你好运
L"COM3", //串口编号 L什么意思?