C++ 中的串行端口 (RS -232) 连接 [英] Serial Port (RS -232) Connection in C++

查看:22
本文介绍了C++ 中的串行端口 (RS -232) 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.h which 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.

推荐答案

请看这里:

1) 您可以在 Windows(包括 MinGW)以及 Linux 上使用它.或者你只能以代码为例.

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

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);

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

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

CloseHandle(serialHandle);

这篇关于C++ 中的串行端口 (RS -232) 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆