c++

C++串口通信如何开始

小樊
82
2024-06-26 11:13:50
栏目: 编程语言

要开始使用C++进行串口通信,首先需要包含相应的头文件并初始化串口参数,然后打开串口进行通信。以下是一个简单的示例代码:

#include <iostream>
#include <string>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>

int main() {
    // 打开串口
    int fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd == -1) {
        std::cerr << "Error opening serial port" << std::endl;
        return 1;
    }
    
    // 配置串口参数
    struct termios tty;
    if (tcgetattr(fd, &tty) != 0) {
        std::cerr << "Error getting serial port attributes" << std::endl;
        return 1;
    }
    
    tty.c_cflag &= ~PARENB; // 无校验位
    tty.c_cflag &= ~CSTOPB; // 1个停止位
    tty.c_cflag |= CS8; // 8位数据位
    tty.c_cflag &= ~CRTSCTS; // 禁用硬件流控
    tty.c_cflag |= CREAD | CLOCAL; // 启用接收器和忽略调制解调器状态
    tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // 原始模式
    
    cfsetospeed(&tty, B9600); // 设置波特率为9600
    cfsetispeed(&tty, B9600);
    
    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        std::cerr << "Error setting serial port attributes" << std::endl;
        return 1;
    }
    
    // 发送数据
    std::string message = "Hello, serial port!";
    int bytes_written = write(fd, message.c_str(), message.length());
    if (bytes_written < 0) {
        std::cerr << "Error writing to serial port" << std::endl;
        return 1;
    }
    
    // 关闭串口
    close(fd);
    
    return 0;
}

在上面的示例中,程序打开了串口/dev/ttyUSB0,配置了波特率和数据位等参数,然后向串口发送了一条消息。您可以根据自己的需求更改串口路径、波特率、发送的数据等内容。记得在使用串口通信时要注意数据的收发顺序和数据的解析。

0
看了该问题的人还看了