• 正文
  • 相关推荐
申请入驻 产业图谱

Linux下创建虚拟终端(虚拟串口)

06/17 15:16
1249
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

在Linuux下可以通过创建虚拟终端的方法来做为虚拟串口使用,创建的虚拟终端,在建立一个软链接,原来的串口程序可以直接当串口访问,不需要改动原程序的代码。

代码

#include?<stdio.h>
#include?<stdlib.h>
#include?<fcntl.h>
#include?<unistd.h>
#include?<string.h>
#include?<errno.h>
#include?<sys/types.h>
#include?<sys/stat.h>
#include?<termios.h>

#define?BUFFER_SIZE 256

// 配置串口参数
void?configure_serial(int?fd,?int?baud_rate)?{
? ??structtermios?options;
? ??tcgetattr(fd, &options);?// 获取当前串口配置
? ??cfsetispeed(&options, baud_rate);?// 设置输入波特率
? ??cfsetospeed(&options, baud_rate);?// 设置输出波特率
? ? options.c_cflag |= (CLOCAL | CREAD);?// 本地连接,接收使能
? ? options.c_cflag &= ~PARENB;?// 无奇偶校验
? ? options.c_cflag &= ~CSTOPB;?// 1个停止位
? ? options.c_cflag &= ~CSIZE;?// 清除数据位掩码
? ? options.c_cflag |= CS8;?// 设置8位数据
? ??tcsetattr(fd, TCSANOW, &options);?// 应用配置
}

int?main()?{
? ??int?master_fd, slave_fd;
? ??char?*slave_name;
? ??char?buffer[BUFFER_SIZE];
? ??int?n;

? ??// 打开伪终端主设备
? ? master_fd =?posix_openpt(O_RDWR | O_NOCTTY);
? ??if?(master_fd ==?-1) {
? ? ? ??perror("posix_openpt");
? ? ? ??return?EXIT_FAILURE;
? ? }

? ??// 授权访问
? ??if?(grantpt(master_fd) ==?-1) {
? ? ? ??perror("grantpt");
? ? ? ??close(master_fd);
? ? ? ??return?EXIT_FAILURE;
? ? }

? ??// 解锁伪终端
? ??if?(unlockpt(master_fd) ==?-1) {
? ? ? ??perror("unlockpt");
? ? ? ??close(master_fd);
? ? ? ??return?EXIT_FAILURE;
? ? }

? ??// 获取从设备的名称
? ? slave_name =?ptsname(master_fd);
? ??if?(slave_name ==?NULL) {
? ? ? ??perror("ptsname");
? ? ? ??close(master_fd);
? ? ? ??return?EXIT_FAILURE;
? ? }

? ??printf("Virtual Serial Port created: %sn", slave_name);

? ??// 配置主设备的串口参数
? ??configure_serial(master_fd, B9600);

? ??// 主循环:监听数据并处理
? ??while?(1) {
? ? ? ??// 从主设备读取数据
? ? ? ? n =?read(master_fd, buffer, BUFFER_SIZE -?1);
? ? ? ??if?(n >?0) {
? ? ? ? ? ? buffer[n] =?'';?// 确保字符串以空字符结尾
? ? ? ? ? ??printf("Received: %sn", buffer);

? ? ? ? ? ??// 处理数据(这里简单地返回相同的数据)
? ? ? ? ? ??write(master_fd, buffer,?strlen(buffer));
? ? ? ? }?elseif?(n ==?0) {
? ? ? ? ? ??printf("Connection closedn");
? ? ? ? ? ??break;
? ? ? ? }?else?{
? ? ? ? ? ??perror("read");
? ? ? ? ? ??break;
? ? ? ? }
? ? }

? ??// 关闭文件描述符
? ??close(master_fd);

? ??return0;
}

编译运行

这里设置的波特率好像不生效的

aarch64-linux-gnu-gcc virtual_tty_main.cpp -o vcom

下载到板子上运行
./vcom?
Virtual Serial Port created: /dev/pts/3

/dev/pts/3即为虚拟终端的节点,为了方便使用,可以在代码里将这个节点建立个软链接,比如:

ln?-s /dev/pts/3 ? /dev/com4?

相关推荐

登录即可解锁
  • 海量技术文章
  • 设计资源下载
  • 产业链客户资源
  • 写文章/发需求
立即登录