我对COM端口编程很陌生,目前正处于基础,寻求建议。为了检查COM端口,我使用CreateFile()函数是否正确?并检查我的哪个COM端口是打开的,是在每个COM端口上调用此函数的唯一方法吗?
在前进的同时还有什么我应该记住的吗?现在我只是在基础知识,并感谢任何帮助。感谢。
修改
这是我的代码到目前为止,但COM端口1-10失败或我做错了。
#include <string>
#include <Windows.h>
#include <conio.h>
#include <iostream>
#include <sstream>
int main(){
std::string com = "\\\\.\\COM";
std::string portname;
HANDLE hCom;
for( int i = 1; i<10; i++)
{
std::stringstream sstm;
std::cout << "Trying "<< i<<"\n";
sstm << com << i;
portname = sstm.str();
TCHAR *szPort = (TCHAR*)(portname.c_str());
hCom = CreateFile(szPort,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
if (hCom == INVALID_HANDLE_VALUE)
{
DWORD err=GetLastError();
std::cout << "Failed\n";
}
else
{
std::cout << i << " Didn't Fail o.o";
CloseHandle(hCom);
}
}
return 0;
}
编辑2: 我也尝试使用
手动调用该函数hCom = CreateFile("\\\\.\\COM1",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
使用COM 1-10切换\\。\ COM1并继续从GetLastError()获取错误2。