简单的RS-232串口通信代码示例

        一个简单的 C++ 程序,它通过串口向设备发送一个字节数据 0x55。它首先打开串口设备 /dev/ttyUSB0,然后等待 5 秒钟,以确保设备已准备好。接着配置串口参数,包括波特率、数据位、停止位等。最后,使用 write() 函数向串口写入数据,并输出发送的字节数。

serial_communication.cpp

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


int main() {
    // 打开串口设备
    int serial_port = open("/dev/ttyUSB0", O_RDWR);
    if (serial_port == -1) {
        std::cerr << "无法打开串口设备" << std::endl;
        return 1;
    }
    // 等待 5 秒钟
    sleep(5);
    // 配置串口参数
    struct termios tty;
    memset(&tty, 0, sizeof(tty));
    if (tcgetattr(serial_port, &tty) != 0) {
        std::cerr << "无法获取串口参数" << std::endl;
        return 1;
    }
    tty.c_cflag &= ~PARENB;  // 禁用奇偶校验
    tty.c_cflag &= ~CSTOPB;  // 一位停止位
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;      // 8位数据位
    tty.c_cflag |= CREAD | CLOCAL;  // 启用接收器和本地模式
    tty.c_lflag &= ~ICANON; // 禁用规范模式
    tty.c_lflag &= ~ECHO;   // 禁用回显
    tty.c_oflag &= ~OPOST;  // 输出模式设置为原始数据

    cfsetispeed(&tty, B115200); // 设置输入波特率为115200
    cfsetospeed(&tty, B115200); // 设置输出波特率为115200

    if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
        std::cerr << "无法设置串口参数" << std::endl;
        return 1;
    }

    // 向串口写入数据
    unsigned char data[] = {0x55};
    int bytes_written = write(serial_port, data, sizeof(data));
    if (bytes_written == -1) {
        std::cerr << "无法写入数据" << std::endl;
        return 1;
    }
    std::cout << "已发送 " << bytes_written << " 字节数据" << std::endl;

    // 关闭串口
    close(serial_port);

    return 0;
}
  • CMakeList.txt

cmake_minimum_required(VERSION 3.0)
project(serial_communication)

# 设置 C++ 标准
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# 添加可执行文件
add_executable(serial_communication serial_communication.cpp)

# 查找并链接串口库
find_package(Threads REQUIRED)
target_link_libraries(serial_communication Threads::Threads)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

点云兔子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值