C++ 中的串行端口 (RS -232) 连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15794422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:46:05  来源:igfitidea点击:

Serial Port (RS -232) Connection in C++

c++serial-portmingw

提问by iammurtaza

I have done serial port RS-232 connection in C++ using 16-bit compiler (I was using Turbo C++ IDE). It included header file bios.hwhich contain all the required functions for reading values from the port. Now I want to read value from serial port using C++ 32-bit Mingw compiler. I am using Dev CPP as my IDE. Here I could not find bios.h. Are there any special header files available for this purpose in Mingw? I am using 32-bit compiler now because in my college project I got to use Exception handling which I guess is not supported in Turbo C. Please help me out.

我已经使用 16 位编译器在 C++ 中完成了串口 RS-232 连接(我使用的是 Turbo C++ IDE)。它包括头文件bios.h,其中包含从端口读取值所需的所有函数。现在我想使用 C++ 32 位 Mingw 编译器从串口读取值。我使用 Dev CPP 作为我的 IDE。我在这里找不到bios.h。Mingw 中是否有任何特殊的头文件可用于此目的?我现在使用 32 位编译器,因为在我的大学项目中,我必须使用异常处理,我猜 Turbo C 不支持它。请帮帮我。

回答by ollo

Please take a look here:

请看这里:

1)You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.

1)您可以在 Windows(包括 MinGW)和 Linux 上使用它。或者,您只能使用代码作为示例。

2)Step-by-step tutorial how to use serial ports on windows

2)分步教程如何在 windows 上使用串口

3)You can use this literally on MinGW

3)你可以在 MinGW 上直接使用它

Here's some very, very simple code (without any error handling or settings):

这是一些非常非常简单的代码(没有任何错误处理或设置):

#include <windows.h>

/* ... */


// Open serial port
HANDLE serialHandle;

serialHandle = CreateFile("\\.\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);

GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);

// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;

SetCommTimeouts(serialHandle, &timeout);

Now you can use WriteFile()/ ReadFile()to write / read bytes. Don't forget to close your connection:

现在您可以使用WriteFile()/ReadFile()写入/读取字节。不要忘记关闭您的连接:

CloseHandle(serialHandle);

回答by Mi Po

For the answer above, the default serial port is

对于上面的答案,默认的串口是

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;