Pyserial写入数据但不读取

时间:2016-01-21 17:44:17

标签: python serial-port pyserial

我对编程比较陌生,所以请耐心等待。我尝试使用Windows 7 64位操作系统测试设备METEX M-4650CR https://sigrok.org/wiki/Voltcraft_M-4650CR和我进行通信。我只是想读出设备测量的数据到我的python程序并显示它并用它计算。

我在手册http://elektron.pol.lublin.pl/elekp/labor_instr/METEX_M-4650CR_Manual.pdf(第25页)中找到了波特率为1200 字节大小为7 (使用ASCII编码)和 2 stopbits

此外,可以通过简单地给它命令" M"来请求将数据发送到计算机。然后它将 14个字节返回给计算机。没有任何与之相关的测量值,它应该返回类似于DC 00.0000V CR'的东西。 CR是这里的终结者(我希望这是正确的名称)。

这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate as scp

y = [ 815.97,  815.95,  815.98,  ...,  815.9] #60 elements
x = [405383892, 405383894, 405383895, ..., 405383896] #60 elements

mediana = np.median(x)
f = scp.interp1d(x,y,bounds_error=False,fill_value=0.,kind='cubic')
new_x_array = np.arange(min(x),max(x),0.01)
plt.figure()    
plt.plot(new_x_array,f(new_x_array),'r-')
plt.plot([x[0],x[59]], [mediana,mediana], 'g-')
plt.plot(x, y, 'mo')

我的问题是,我无法使用pyserial正确读出数据。我发送命令" M"在METEX和显示屏上它表示发送'一会儿,我想我的写命令工作正常。但在那之后(它应该发送数据),我从import pyserial import time ser = serial.Serial(port='COM5', baudrate=1200, bytesize=7, stopbits=2, timeout=1, rtscts=False, dsrdtr=True) time.sleep(1) ser.write("M") time.sleep(1) bytestoread = ser.inWaiting() print bytestoread output = '' output += ser.read(1000) print 'output:' + str(output) time.sleep(1) ser.close() 获得的所有内容都是' 0L'或者' 1L'并且ser.inWaitung命令根本不提供任何内容。

我不认为这是硬件问题,因为使用另一个称为“串行报警器”的程序,我能够正确读出数据。它完全给出了手册中描述的字符。

我也尝试了以下while循环,遇到问题,大部分时间都是ser.read,这样它就不会初始化循环。

inWaiting == 0

那么,如何才能正确读出发送到串口的数据呢?提前谢谢。

1 个答案:

答案 0 :(得分:1)

不幸的是我无法测试您的代码,因为我没有串行设备,但您可以尝试以下操作:

你可以设置一个标志,例如alive当您期待数据并且只是尝试阅读某些内容时。当我试图从一台非常古老的光谱仪接收数据时,这对我有用。

     while alive:                          #loop
        text = ser.read(1)                 #try to read one line
        if text:                           #if there is data
            n = ser.inWaiting()            #look if there is more to read
            if n:                          #if so
                text = text + ser.read(n)  #get all of it

这里可以找到一个更复杂的例子wxTerminal - Pyserial example你也可以简单地尝试修改这个出色的代码,看看你是否更成功。

相关问题