【问题标题】:Trouble sending data from Matlab to Python via serial port通过串口将数据从 Matlab 发送到 Python 时遇到问题
【发布时间】:2019-10-09 21:06:13
【问题描述】:

为了更好地理解串口通信,我正在尝试编写一些示例代码,其中 Matlab 有一个循环运行,它不断地将数据发送到串口,而在同一台 windows 机器上运行的 Python 脚本监听这个端口,然后接收并打印任何接收到的数据。

在Matlab中,我写了一个简单的循环,将99个测试信号发送到端口COM1,

% Setup a serial port and open it
tep=serial("COM1", "Baudrate", 9600);
fopen(tep);

% this loop is supposed to send a number to a serial port repeatedly
n = 1; % counter variable
while n < 100
    fprintf(tep,"50"); % Send data to serial port
    n = n + 1;      % Counter variable
    pause(0.5)      % Sleep to make this loop run for a total of 50s0
    fprintf('run'); % Test output within matlab to check, whether it runs
end

% finally close the serial port
fclose(tep);

据我所知,这个 Matlab 部件可以工作,因为它每隔半秒就会打印一次“运行”。

Python 监听器:

import serial
import time
# set up the serial line same as in Matlab
ser = serial.Serial('COM1', 9600)
time.sleep(2)

# Read and record the data
data =[]                       # empty list to store the data
for i in range(50):
    b = ser.readline()         # read a byte string
    string_n = b.decode()  # decode byte string into Unicode  
    string = string_n.rstrip() # remove \n and \r
    flt = float(string)        # convert string to float
    print(flt)
    data.append(flt)           # add to the end of data list
    time.sleep(0.1)            # wait (sleep) 0.1 seconds

ser.close()

# show the data

for line in data:
    print(line)

在 Python 中运行脚本会导致以下错误:

serial.serialutil.SerialException: could not open port 'COM1': PermissionError(13, 'Zugriff verweigert', None, 5)

显然,Matlab 已经在使用该端口,因为它向它发送信息,但我不明白,为什么这是一个问题。一个程序向它发送数据,另一个程序从它接收数据不是很好吗?

亲切的问候。

【问题讨论】:

    标签: python-3.x matlab serial-port pyserial


    【解决方案1】:

    恐怕你不能从两个不同的进程连接到同一个串口。

    这意味着如果您从 Matlab 打开串行端口进行写入,您将无法从 Python 打开它进行读取。

    串行端口旨在将数据从一台计算机发送到另一台计算机或设备,而不是在不同的应用程序之间共享数据(为此,有更好的方法,例如写入文件或一大块共享内存)。

    话虽如此,如果您尝试做的是出于调试目的或只是为了学习,您可能想调查com0com,它允许您创建一对虚拟(软件)串行端口.这与将几个硬件(实际)串行端口相互连接起来是一样的。由于现在您有两个端口,您可以在一个端口上从 Matlab 发送数据,在另一个端口上从 Python 读取数据。

    这是关于串口最常见的问题之一,所以你应该可以找到很多好的资源。你可能想开始here

    【讨论】:

    • 使用虚拟串口驱动程序让我从 Matlab 发送数据并将其导入 python。非常感谢
    • 太好了,很高兴我的回答很有用
    猜你喜欢
    • 2021-11-04
    • 2021-02-21
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 2014-09-22
    相关资源
    最近更新 更多