使用PySerial从Ardunio获取更新仅每2分钟而不是1分钟

时间:2016-11-26 15:19:25

标签: python arduino pyserial

我有一个Arduino报告时间(以秒为单位),电压,电流和焦耳60秒。在这样的串行监视器中:

time,voltage,current,joules
60,1.45,0.39,0.57
120,1.45,0.39,1.13
180,1.45,0.39,1.70
240,1.45,0.39,2.26
...

但是下面的python脚本我得不到这个结果:

import serial
ser = serial.Serial('COM5', 9600)
logfile = open("batterytest.log", 'w')
while True:
    if ser.readline() == b'Test Complete!':
        logfile.close()
        exit()
    logfile.write(ser.readline().decode("utf-8"))
    logfile.flush()

相反,我每120秒看一次结果:

time,voltage,current,joules
120,1.13,0.02,0.05
240,1.13,0.02,0.09
360,1.13,0.02,0.14
480,1.13,0.02,0.19
....

1 个答案:

答案 0 :(得分:1)

由于某些时间问题,它看起来可能会错过中间数据点。您可以尝试使用putty来查看您的arduino实际上是否输出了正确的数据点。

对于你的PySerial程序,我会添加一个变量" data"首先存储您的串行读取线,然后在其上执行您的逻辑。

import serial
ser = serial.Serial('COM5', 9600)
logfile = open("batterytest.log", 'w') 
while True:
    data = ser.readline()
    if data == b'Test Complete!':
        logfile.close()
        exit()
    logfile.write(data.decode("utf-8"))
    logfile.flush()

此外,根据您的Arduino输出时序,您可以考虑为序列读取添加超时值:

ser = serial.Serial('COM5', 9600, timeout = 1 )
# Here the time out is 1 second