linux c++ 串口发送
时间: 2025-02-12 19:59:47 浏览: 21
如何在 Linux 环境下用 C++ 实现串口通信发送数据
要在 Linux 下通过 C++ 进行串口通信并发送数据,需设置好开发环境,包括拥有支持串口通信的 Linux 操作系统、安装有 g++ 编译器等工具链,并准备好相应的硬件连接[^1]。
下面展示一段用于打开指定端口、配置该端口参数以及向其写入字符串消息至外部设备的简单程序片段:
#include <iostream>
#include <string>
#include <cstring> // For memset function.
#include <fcntl.h> // File control definitions.
#include <termios.h> // POSIX terminal control definition.
#include <unistd.h> // UNIX standard function definitions.
using namespace std;
int main() {
const char* deviceName = "/dev/ttyS0"; // Serial port name, may vary on different systems.
int serialPortDescriptor;
// Open the serial port with read/write permission and non-blocking mode disabled (O_NOCTTY prevents this process from becoming a controlling terminal).
if ((serialPortDescriptor = open(deviceName, O_RDWR | O_NOCTTY)) == -1) {
cerr << "Failed to open serial port." << endl;
return -1;
}
struct termios ttyOptions;
tcgetattr(serialPortDescriptor, &ttyOptions); // Get current attributes of the specified terminal.
cfsetospeed(&ttyOptions, B9600); // Set output baud rate as 9600 bits per second.
cfsetispeed(&ttyOptions, B9600); // Set input baud rate similarly.
ttyOptions.c_cflag |= (CLOCAL | CREAD); // Enable receiver and set local mode so that no modem controls are required.
ttyOptions.c_cflag &= ~PARENB; // Disable parity bit.
ttyOptions.c_cflag &= ~CSTOPB; // Use one stop bit.
ttyOptions.c_cflag &= ~CSIZE; // Mask the character size bits.
ttyOptions.c_cflag |= CS8; // Select 8 data bits.
ttyOptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Raw input rather than cooked input.
ttyOptions.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl.
ttyOptions.c_oflag &= ~OPOST; // Prevent special handling of received bytes by disabling post-processing.
tcsetattr(serialPortDescriptor, TCSANOW, &ttyOptions); // Apply options immediately without waiting for pending I/O operations to complete.
string messageToSend = "Hello World\n";
ssize_t numBytesWritten = write(serialPortDescriptor, messageToSend.c_str(), messageToSend.length());
cout << "Number of bytes written: " << numBytesWritten << endl;
close(serialPortDescriptor);
return 0;
}
这段代码展示了如何初始化串口属性以便于后续的数据传输操作。这里选择了常见的波特率(9600bps)、字符长度(8位)、停止位数量(1个),并且禁用了奇偶校验等功能以简化配置过程[^2]。
相关推荐


















