2017-05-03 82 views
0

我有以下用於檢測CO2水平的代碼。 以下是關於模型的一些信息。Co2 k30傳感器不能與Raspberry Pi一起使用3

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) 

我沒有獲得一致的輸出。

我得到的東西下面

[email protected]:~/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 
[email protected]:~/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 
[email protected]:~/i2c $ 

感謝所有幫助?

+0

您應該在編制索引之前檢查結果內容。顯然,你所期望的結果列較少。 – Carcigenicate

回答

0

high = ord(resp[3])

IndexError: string index out of range

這意味着字符串resp的長度爲0對於該特定呼叫和代碼試圖指向串的第三元件。這就是爲什麼你的索引超出範圍。

如果您嘗試在每次迭代中看到len(rep),您將在發生錯誤的特定迭代中得到0,但由於您在開始時有數據,這意味着您至少能夠讀取您的串行端口。

可能問題在於傳感器電源/ gnd甚至RX/TX引腳的連接鬆動。

你可以分享你究竟做了什麼從PI3的串行端口獲取數據或嘗試做:sudo chmod g + r/dev/ttyS0?

+0

這是1/2回答和1/2問題,請只回答問題,如果您需要詢問另一個問題您[問]界面。 –

相關問題