• 正文
  • 相關(guān)推薦
申請(qǐng)入駐 產(chǎn)業(yè)圖譜

Linux下創(chuàng)建虛擬終端(虛擬串口)

4小時(shí)前
24
加入交流群
掃碼加入
獲取工程師必備禮包
參與熱點(diǎn)資訊討論

在Linuux下可以通過(guò)創(chuàng)建虛擬終端的方法來(lái)做為虛擬串口使用,創(chuàng)建的虛擬終端,在建立一個(gè)軟鏈接,原來(lái)的串口程序可以直接當(dāng)串口訪(fǎng)問(wèn),不需要改動(dòng)原程序的代碼。

代碼

#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

// 配置串口參數(shù)
void?configure_serial(int?fd,?int?baud_rate)?{
? ??structtermios?options;
? ??tcgetattr(fd, &options);?// 獲取當(dāng)前串口配置
? ??cfsetispeed(&options, baud_rate);?// 設(shè)置輸入波特率
? ??cfsetospeed(&options, baud_rate);?// 設(shè)置輸出波特率
? ? options.c_cflag |= (CLOCAL | CREAD);?// 本地連接,接收使能
? ? options.c_cflag &= ~PARENB;?// 無(wú)奇偶校驗(yàn)
? ? options.c_cflag &= ~CSTOPB;?// 1個(gè)停止位
? ? options.c_cflag &= ~CSIZE;?// 清除數(shù)據(jù)位掩碼
? ? options.c_cflag |= CS8;?// 設(shè)置8位數(shù)據(jù)
? ??tcsetattr(fd, TCSANOW, &options);?// 應(yīng)用配置
}

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

? ??// 打開(kāi)偽終端主設(shè)備
? ? master_fd =?posix_openpt(O_RDWR | O_NOCTTY);
? ??if?(master_fd ==?-1) {
? ? ? ??perror("posix_openpt");
? ? ? ??return?EXIT_FAILURE;
? ? }

? ??// 授權(quán)訪(fǎng)問(wèn)
? ??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;
? ? }

? ??// 獲取從設(shè)備的名稱(chēng)
? ? 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);

? ??// 配置主設(shè)備的串口參數(shù)
? ??configure_serial(master_fd, B9600);

? ??// 主循環(huán):監(jiān)聽(tīng)數(shù)據(jù)并處理
? ??while?(1) {
? ? ? ??// 從主設(shè)備讀取數(shù)據(jù)
? ? ? ? n =?read(master_fd, buffer, BUFFER_SIZE -?1);
? ? ? ??if?(n >?0) {
? ? ? ? ? ? buffer[n] =?'';?// 確保字符串以空字符結(jié)尾
? ? ? ? ? ??printf("Received: %sn", buffer);

? ? ? ? ? ??// 處理數(shù)據(jù)(這里簡(jiǎn)單地返回相同的數(shù)據(jù))
? ? ? ? ? ??write(master_fd, buffer,?strlen(buffer));
? ? ? ? }?elseif?(n ==?0) {
? ? ? ? ? ??printf("Connection closedn");
? ? ? ? ? ??break;
? ? ? ? }?else?{
? ? ? ? ? ??perror("read");
? ? ? ? ? ??break;
? ? ? ? }
? ? }

? ??// 關(guān)閉文件描述符
? ??close(master_fd);

? ??return0;
}

編譯運(yùn)行

這里設(shè)置的波特率好像不生效的

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

下載到板子上運(yùn)行
./vcom?
Virtual Serial Port created: /dev/pts/3

/dev/pts/3即為虛擬終端的節(jié)點(diǎn),為了方便使用,可以在代碼里將這個(gè)節(jié)點(diǎn)建立個(gè)軟鏈接,比如:

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

相關(guān)推薦

登錄即可解鎖
  • 海量技術(shù)文章
  • 設(shè)計(jì)資源下載
  • 產(chǎn)業(yè)鏈客戶(hù)資源
  • 寫(xiě)文章/發(fā)需求
立即登錄