我通过以下python程序读取了串行数据。
import serial
import time
ser = serial.Serial('COM1', 9600, timeout=0)
var = '\x11\x02\x01\x00\xEC'
ser.write(var)
time.sleep(1)
while True:
try:
Data_in = ser.readline().encode('hex')
DF1 = Data_in [6:8]
DF2 = Data_in [8:10]
CO2 = int(DF1, 16)*256 + int(DF2, 16)
print "=========================="
print "Found Packet: " + Data_in
print "DF 1: " + DF1 + " DF2: " + DF2 + " | CO2 : " + CO2
time.sleep(1)
except ser.SerialTimeoutException:
print('Data could not be read')
除CO2外,输出成功返回:
如果我想通过以下公式计算数据,python程序将返回错误。
CO2 = int(DF1,16)* 256 + int(DF2,16)
错误 Traceback(最近一次调用最后一次): 文件" C:\ Users \ UserPC \ workspace \ aqi \ testserialv1.py",第40行,在 除了ser.SerialTimeoutException: AttributeError:' Serial' object没有属性' SerialTimeoutException'
答案 0 :(得分:0)
感谢CivFan给出的评论。我修改代码后
serial.SerialTimeoutException
它工作正常。这是完整的代码
import serial
import time
ser = serial.Serial('COM1', 9600, timeout=0)
var = '\x11\x02\x01\x00\xEC'
while True:
try:
ser.write(var)
time.sleep(1)
Data_in = ser.readline().encode('hex')
print "=========================="
print "Found Packet: " + Data_in
Data_length = int( Data_in [2:4], 16)
if Data_length == 11:
DF1 = int( Data_in [6:8], 16)
DF2 = int( Data_in [8:10], 16)
CO2 = DF1*256.0 + DF2
DF3 = int( Data_in [10:12], 16)
DF4 = int( Data_in [12:14], 16)
VOC = (DF3* 256 + DF4) / 100.0
DF5 = int( Data_in [14:16], 16 )
DF6 = int( Data_in [16:18], 16 )
RH = (DF5*256.0 + DF6) / 10.0
DF7 = int( Data_in [18:20], 16)
DF8 = int( Data_in [20:22], 16)
Temp = (DF7*256.0 + DF8-500) / 10.0
DF9 = int( Data_in [22:24], 16)
DF10 = int( Data_in [24:26], 16)
PM25 = DF9*256.0 + DF10
print "CO2 : " + str(CO2) + " VOC : " + str(VOC) + " RH : " + str(RH) + " Temp : " + str(Temp) + " PM : " + str(PM25)
time.sleep(5)
except serial.SerialTimeoutException:
print('Data could not be read')