【问题标题】:Co2 k30 sensor not working with Raspberry pi 3Co2 k30 传感器不适用于 Raspberry pi 3
【发布时间】: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


【解决方案1】:

high = ord(resp[3])

IndexError: 字符串索引超出范围

这意味着该特定调用的字符串resp 的长度为0,并且代码试图指向字符串的第三个元素。这就是索引超出范围的原因。

如果您尝试在每次迭代中查看len(rep),您将在发生错误的特定迭代中得到 0,但由于您在开始时拥有数据,这意味着您至少能够读取您的串行端口。

问题可能在于传感器的电源/接地甚至 RX/TX 引脚连接松动。

你能分享一下你究竟做了什么来从 PI3 的串口获取数据或尝试做:sudo chmod g+r /dev/ttyS0?

【讨论】:

  • 这是1/2答案和1/2问题,请仅通过答案,如果您需要在How to Ask界面提出其他问题。
猜你喜欢
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 2021-12-02
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多