简体   繁体   English

C ++ COM端口打开,读取和写入

[英]C++ COM port Opening, Reading and Writing

I am trying to open a COM port using Win32's CreateFile function. 我正在尝试使用Win32的CreateFile函数打开COM端口。 I have read docs at MSDN as well as on several forums on how to do that but no matter what I do I still get Error code #2 (port does not exist). 我已经在MSDN以及一些论坛上阅读了有关如何执行此操作的文档,但是无论我做什么我仍然会收到错误代码2(端口不存在)。 The code I currently have is: 我目前拥有的代码是:

m_hCom = CreateFile(
    "\\.\COM10",
    GENERIC_READ | GENERIC_WRITE,
    0,
    0,
    OPEN_EXISTING,
    FILE_FLAG_OVERLAPPED,
    NULL
);
if (m_hCom == INVALID_HANDLE_VALUE) {
    int error = GetLastError();
    return FALSE;
}

I am using Visual Studio 2010. 我正在使用Visual Studio 2010。

Please tell me what am I doing wrong. 请告诉我我在做什么错。

Try putting in some extra slashes like this: 尝试像这样添加一些额外的斜杠:

"\\\\\\\\.\\\\COM10" “ \\\\\\\\。\\\\ COM10”

Because the backslash is a special character you have to insert two for each one you want in your string. 由于反斜杠是特殊字符,因此您必须在字符串中为每个字符插入两个。

尝试这个:

CreateFile(L"COM1", ...);

Run the following code in a C++ Project and if the Comport let's say COMPORT 4 is taken by let's say TeraTerm it sends back an error otherwise it opens up the port. 在C ++项目中运行以下代码,如果Comport假设COMPORT 4被TeraTerm占用,它将发回错误,否则将打开端口。

HANDLE hComm; 处理hComm;
hComm = CreateFile( hComm = CreateFile(
L"\\\\.\\COM4", L“ \\\\。\\ COM4”,
GENERIC_READ | GENERIC_READ | GENERIC_WRITE, GENERIC_WRITE,
0, 0,
0, 0,
OPEN_EXISTING, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, FILE_FLAG_OVERLAPPED,
NULL 空值
); );
if (hComm == INVALID_HANDLE_VALUE) { 如果(hComm == INVALID_HANDLE_VALUE){
printf("The Comport is closed or taken by another hardware/software!\\n\\r"); printf(“ Comport已关闭或被其他硬件/软件占用!\\ n \\ r”);
} }

I suggest writing some temporary code that iterates or lists the available COM ports. 我建议编写一些临时代码来迭代或列出可用的COM端口。

There is a great chance that your COM port naming is not correct. 您的COM端口命名很可能不正确。

I have written the same code you are trying to write not long ago. 我已经写了不久前试图编写的相同代码。 If you say there is a 10th COM port then it should work as long as you have the extra slashes. 如果您说有第10个COM端口,那么只要您有多余的斜杠,它就应该起作用。 You can trying going the projects property window and changing the Character Set to multibyte characters. 您可以尝试进入项目属性窗口,然后将字符集更改为多字节字符。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM