【发布时间】:2017-05-03 14:57:14
【问题描述】:
我有以下代码正在运行以检测二氧化碳水平。 以下是有关模型的一些信息。
CO2 传感器 - K30 树莓派 3
我已经按照以下文档在 pi 和 k-30 之间建立了连接 http://www.co2meters.com/Documentation/AppNotes/AN137-K30-sensor-raspberry-pi-uart.pdf
下面是我的python代码
import serial
import time
ser = serial.Serial("/dev/ttyS0",baudrate =9600,timeout = .5)
print " AN-137: Raspberry Pi3 to K-30 Via UART\n"
ser.flushInput()
time.sleep(1)
for i in range(1,21):
ser.flushInput()
time.sleep(1)
ser.write("\xFE\x44\x00\x08\x02\x9F\x25")
time.sleep(1)
resp = ser.read(7)
high = ord(resp[3])
low = ord(resp[4])
co2 = (high*256) + low
print "i = ",i, " CO2 = " +str(co2)
time.sleep(.5)
我没有得到一致的输出。
我在下面得到了一些东西
pi@raspberrypi:~/i2c $ sudo python test-co2.py
AN-137: Raspberry Pi3 to K-30 Via UART
i = 1 CO2 = 2458
i = 2 CO2 = 2457
i = 3 CO2 = 2448
Traceback (most recent call last):
File "test-co2.py", line 16, in <module>
high = ord(resp[3])
IndexError: string index out of range
pi@raspberrypi:~/i2c $ sudo python test-co2.py
AN-137: Raspberry Pi3 to K-30 Via UART
i = 1 CO2 = 2207
Traceback (most recent call last):
File "test-co2.py", line 16, in <module>
high = ord(resp[3])
IndexError: string index out of range
pi@raspberrypi:~/i2c $
感谢任何帮助?
【问题讨论】:
-
您应该在索引之前检查结果内容。显然结果列比您预期的要少。
标签: python iot raspberry-pi3