【问题标题】:I'm trying to read sensor data through serial communication but when I try to read it just kept on runnin in python but it doesn't display any value我正在尝试通过串行通信读取传感器数据,但是当我尝试读取它时,它只是在 python 中运行,但它没有显示任何值
【发布时间】:2021-05-04 16:16:09
【问题描述】:

我将光探测器传感器连接到数据采集盒,它通过 RS232 USB 电缆连接到我的笔记本电脑。我已经在 python 中稳定了与该端口的串行通信。但是当我尝试读取数据时,它只是继续运行并且不显示任何值。我在 MATALB 中尝试过同样的想法,它工作正常,所以我知道端口和传感器工作正常。我只是无法读取 python 中的数据。我有三种方法(如下python代码所示)但没有任何效果。请帮帮我。

这是我的python代码:

import serial
from serial import Serial

s = serial.Serial('COM3')  # open serial port
print(ser.name)         

# Set the serial port to desired COM 
s = serial.Serial(port = 'COM3', bytesize = serial.EIGHTBITS, parity = serial.PARITY_NONE, baudrate = 9600, stopbits = serial.STOPBITS_ONE)

# Read the data(method 1)
while 1:
    while (s.inWaiting() > 0):
        try:
            inc = s.readline().strip()
            print(inc)
         
# Read the data(method 2)        
data = str(s.read(size = 1))
print(data)

# Read all the data(method 3)
while i <10:
    b = s.readlines(100) # reading all the lines

【问题讨论】:

  • 设备是否输出换行符?快速查看pyserial.readthedocs.io/en/latest/shortintro.html 表明您想要s.read
  • 我不确定。我什至如何检查。当我在 matlab 中执行此操作时,它给出了带有空格但在同一行中的值。我也尝试过 s.read ,但它没有返回任何值。它只是继续运行(执行)代码,但不显示任何值。
  • 我运行了代码,它在 print(inc) 行暂停。它不会移动到其他行,甚至不会移动到超时异常。我认为到目前为止的代码读取了端口,但我缺少从 DAQ 的不同通道中提取数据的代码行。在 matlab 中,我使用以下代码读取数据: MATLAB Code: fwrite(s,strcat('#010',hex2dec('0D'))); out1 = fgetl(s) out1 = out1(2:end); out1 = str2num(out1);如果(out1

标签: python-3.x readline pyserial


【解决方案1】:

在 matlab 中它给出的值带有空格但在同一行

这表示设备没有发送换行符。

我从未使用过您的设备或 Python 串行模块。但从文档来看,这就是我要做的:

from time import sleep

while s.is_open():
    n = s.in_waiting()
    if n == 0:
        print "no data"
        sleep(1)
        continue
    try:
        inc = s.read(n)
        print(inc)
    catch serial.SerialException as oops:
        print(oops)
    catch serial.SerialTimeoutException as oops:
        print(oops)
print("serial port closed")

这将为您提供每种情况的反馈:端口打开/关闭、数据准备好/未准备好以及数据(如果有)。从那里你可以弄清楚该怎么做。

documentation 表示inWaiting 已弃用,所以我使用了in_waiting

如果问题在于首先配置串行端口,我不会感到惊讶。串行端口就是那样棘手。

【讨论】:

  • 我运行了代码,它在 print(inc) 行暂停。它不会移动到其他行,甚至不会移动到超时异常。我认为到目前为止的代码读取了端口,但我缺少从数据采集框的不同通道中提取数据的代码行。在 matlab 中设置串口后,我使用此代码读取数据: MATLAB Code: % Sensor 1 data fwrite(s,strcat('#010',hex2dec('0D'))); out1 = fgetl(s) out1 = out1(2:end); out1 = str2num(out1); out1 = 9375*out1-37500+93.75 % 将 mA 转换为 lux if(out1
  • 我认为“暂停”是指它在print(inc) 之前停止,这意味着读取被阻塞。我不知道 Matlab,但fwrite(s,strcat('#010',hex2dec('0D'))); 看起来您首先要写入 到设备,特别是字符串“#010\r”,我使用“\r”表示回车,十六进制为0D。如果是这样,您可能需要在 Python 中在 read 语句之前使用类似的 s.write
猜你喜欢
  • 1970-01-01
  • 2021-05-17
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-09
  • 2020-01-11
相关资源
最近更新 更多