首页 > 解决方案 > 如何使用 Linux 的虚拟串口使 C 程序与 Python 程序通信?

问题描述

我想将 C 程序中的数据发送到 Python 程序中,该程序将可视化这些数据。开发环境是一台Linux(Ubuntu 18.04LTS)计算机。更清楚地说,这两个程序都在同一台计算机上运行。

我在 C 程序中使用 termios 打开串口,在 Python 端使用 pySerial。至于串口,我使用的是“ttyS0”。问题是,当我从 C 程序向 Python 程序发送“Hello”并在终端上打印时,我看到的是空格字符,基本上我得到了这个“”。

我的问题是,我可以为此目的使用“ttyS0”串行端口(我猜那是一个虚拟端口)吗?

这是C代码:

#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>
#include <time.h>

// Termios init functions are not posted because the configuration
// is correct and proved that they are working.

int main()
{
    char *portname = "/dev/ttyS0";
    int fd;
    int wlen;
    unsigned char writeBuffer[] = "Hello!";

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);

    do{
        wlen = write(fd, writeBuffer, sizeof(writeBuffer));
        printf("Sent data is: \"%s\"\n", writeBuffer);
        delay(500);
    } while(1);
}

Python代码:

import serial
from time import sleep

port = "/dev/ttyS0"
ser = serial.Serial(port, 115200, timeout=0.5)

while True:
    data = ser.readline()   
    print(str(data.decode('utf-8')))
ser.close()

标签: clinuxserial-portpyserialtermios

解决方案


ttyS0 是您计算机的串行端口——它没有什么“虚拟”的。写入此设备将尝试使用该端口将数据传输出计算机,从该设备读取将尝试从连接到该端口的外部设备接收数据。同一台计算机上的两个程序无法使用串行端口进行有效通信。

我认为您在这里寻找的是pipesocket pairpty。哪一个最合适将取决于您的具体要求。


推荐阅读