一个简单的 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)