c - 如何使用 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()
解决方案
ttyS0 是您计算机的串行端口——它没有什么“虚拟”的。写入此设备将尝试使用该端口将数据传输出计算机,从该设备读取将尝试从连接到该端口的外部设备接收数据。同一台计算机上的两个程序无法使用串行端口进行有效通信。
我认为您在这里寻找的是pipe、socket pair或pty。哪一个最合适将取决于您的具体要求。
推荐阅读
- amazon-web-services - Terraform - AWS EC2 IAM 角色
- google-cloud-platform - 流表上的 BigQuery 删除
- python - 如何在 Python 表中为给定范围添加特定日期的值?
- windows-10 - 在 Windows 10 上无法连接到 Jekyll 的 localhost:4000
- python - 循环用数据做奇怪的事情
- python - 无法将字符串转换为浮点数:'cd9f3b1a-2eb8-4cdb-86d1-5d4c2740b1dc'
- r - 一个长字符到多列
- postgresql - 无法运行赞助人
- selenium - 获取“org.openqa.selenium.WebDriverException: Error forwarding the new session Error forwarding the request Connect to”连接集线器与节点
- angular - 以角度4以编程方式过滤行