Skip to main content
 首页 » 编程设计

python之DMM、Python 和串口 : During a loop之the communication is suddenly stops

2025年05月04日12qlqwjy

我使用安捷伦数字万用表进行测量。 我使用 Python 2.7 和 PySerial 模块与它通信。 想法:使用 FOR 循环,我从 DMM 读取并获取数据。 它在某个时间点之前工作正常,每次都在不同的时间点。

例如:如果我将循环设置为测量 20k 次,它在 1k 次后突然停止,下次尝试它可能会在 5k 次后停止.... stops - 意味着 DMM 停止发送数据,python 保持在一种等待状态。我的脚本卡住了,我必须终止它。没有错误,我不知道为什么。 我尝试在测量之间添加超时( sleep ),但这并不能解决问题。 以下是我的脚本中的主要命令:

# configure the serial connections  
ser = serial.Serial( 
    port='com3', 
    baudrate=19200, 
    parity=serial.PARITY_NONE, 
    stopbits=serial.STOPBITS_ONE, 
    bytesize=serial.EIGHTBITS 
} 
 
 
ser.write("CONF:CURRent:DC" + '\r\n') 
time.sleep(1) 
ser.write("SENS:CURR:DC:RANGe:UPP 0.05" + '\r\n') 
time.sleep(1.5) 
 
for m in range (0, 2000): 
try: 
    ser.write('READ?' + '\r\n') 
    out += ser.read(18) 
    print "out = ",out 
except: 
    print "error!" 

循环正在运行,有时它“存活”到最后但大多数时候它只是停止,请指教。请注意,我从来没有进入“除外”部分。添加“尝试”没有帮助...

谢谢!

~海豚~

请您参考如下方法:

您可以在创建 serial.Serial 对象时设置超时。有 2 个参数用于指定读取和写入超时。这是一个例子:

ser = serial.Serial( 
    port='com3', 
    baudrate=19200, 
    parity=serial.PARITY_NONE, 
    stopbits=serial.STOPBITS_ONE, 
    bytesize=serial.EIGHTBITS, 
    timeout=3, # <------ read timeout in seconds (can be floating) 
    writeTimeout=3, # <-------------- write timeout in seconds (can be floating 
} 

以下是文档中关于这些参数可以采用的值的内容:

timeout = None: wait forever

timeout = 0: non-blocking mode (return immediately on read)

timeout = x: set timeout to x seconds (float allowed)