簡體   English   中英

DHT傳感器Python腳本錯誤

[英]DHT Sensor Python script error

我有一個連接到樹莓派的DHT22型傳感器。 我已經用python編寫了一個腳本,但是當我運行它時出現錯誤

#!/usr/bin/python
import MySQLdb
import subprocess
import re
import sys
import time
import datetime
import Adafruit_DHT

conn = MySQLdb.connect("localhost","zeus","gee3g673r","logi")
while(True):
date = time.strftime("%d/%m/%Y")
clock = time.strftime("%H:%M")

#output = subprocess.check_output(["/usr/bin/AdafruitDHT.py 2302", "4"]);
output = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 4)
matches = re.search("Temp =\s+([0-9.]+)", output)
 if (not matches):
 time.sleep(0)
 continue
temp = float(matches.group(1))

matches = re.search("Hum =\s+([0-9.]+)", output)
 if (not matches):
 time.sleep(0)
 continue
humidity = float(matches.group(1))

# MYSQL DATA Processing
c = conn.cursor()

c.execute("INSERT INTO data_th (date, clock, temp, hum) VALUES (%s, %s,%s, %s)",(date, clock, temp, humidity))

#print "DB Loaded"

time.sleep(360)

這是在運行腳本時遇到的錯誤:

root@raspberrypi:/home# ./hdt.py
Traceback (most recent call last):
File "./dht.py", line 22, in <module>
matches = re.search("Temp =\s+([0-9.]+)", output)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer

Adafruit_DHT.read_retry()不返回字符串。 re.search期望將字符串作為第二個參數。

請看下面的代碼(摘自Adafruit_Python_DHT / examples ):

# Try to grab a sensor reading.  Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32

# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).  
# If this happens try again!
if humidity is not None and temperature is not None:
    print 'Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity)
else:
    print 'Failed to get reading. Try again!'
    sys.exit(1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM