通过原生Python获取

  1. #!/usr/bin/python
  2. #-*- coding:utf-8 -*-
  3. import RPi.GPIO as GPIO
  4. import time
  5. channel = 7 #引脚号Pin7
  6. data = [] #温湿度值
  7. j = 0 #计数器
  8. GPIO.setmode(GPIO.BOARD) #以BOARD编码格式
  9. time.sleep(1) #时延一秒
  10. GPIO.setup(channel, GPIO.OUT)
  11. GPIO.output(channel, GPIO.LOW)
  12. time.sleep(0.02) #给信号提示传感器开始工作
  13. GPIO.output(channel, GPIO.HIGH)
  14. GPIO.setup(channel, GPIO.IN)
  15. while GPIO.input(channel) == GPIO.LOW:
  16. continue
  17. while GPIO.input(channel) == GPIO.HIGH:
  18. continue
  19. while j < 40:
  20. k = 0
  21. while GPIO.input(channel) == GPIO.LOW:
  22. continue
  23. while GPIO.input(channel) == GPIO.HIGH:
  24. k += 1
  25. if k > 100:
  26. break
  27. if k < 8: #通过计数的方式判断是数据位高电平长短,以置0或1。(此方式有待商榷)
  28. data.append(0)
  29. else:
  30. data.append(1)
  31. j += 1
  32. print ("sensor is working.")
  33. print (data) #输出初始数据高低电平
  34. humidity_bit = data[0:8] #分组
  35. humidity_point_bit = data[8:16]
  36. temperature_bit = data[16:24]
  37. temperature_point_bit = data[24:32]
  38. check_bit = data[32:40]
  39. humidity = 0
  40. humidity_point = 0
  41. temperature = 0
  42. temperature_point = 0
  43. check = 0
  44. for i in range(8):
  45. humidity += humidity_bit[i] * 2 ** (7 - i) #转换成十进制数据
  46. humidity_point += humidity_point_bit[i] * 2 ** (7 - i)
  47. temperature += temperature_bit[i] * 2 ** (7 - i)
  48. temperature_point += temperature_point_bit[i] * 2 ** (7 - i)
  49. check += check_bit[i] * 2 ** (7 - i)
  50. tmp = humidity + humidity_point + temperature + temperature_point #十进制的数据相加
  51. if check == tmp: #数据校验,相等则输出
  52. print ("temperature : ", temperature, ", humidity : " , humidity)
  53. else: #错误输出错误信息,和校验数据
  54. print ("wrong")
  55. print ("temperature : ", temperature, ", humidity : " , humidity, " check : ", check, " tmp : ", tmp)
  56. GPIO.cleanup() #重置针脚

通过Python模块获取

  1. 下载模块

github.com/adafruit/Adafruit_Python_DHT.git

  1. 安装模块
    1. cd Adafruit_Python_DHT
    2. sudo python setup.py install
    安装完成后进入examples文件夹运行AdfruitDHT.py可以获得结果。
    1. cd examples
    2. Python AdafruitDHT.py 11 24
    后面两个数值11代表使用的是DHT11模块,24代表着所接的GIPO引脚编号(BCM)。

    在Python中使用该模块

    ```python import Adafruit_DHT

Set sensor type : Options are DHT11,DHT22 or AM2302

sensor=Adafruit_DHT.DHT11

Set GPIO sensor is connected to

GPIO=24

Use read_retry method. This will retry up to 15 times to

get a sensor reading (waiting 2 seconds between each retry).

humidity, temperature = Adafruit_DHT.read_retry(sensor, GPIO)

Reading the DHT11 is very sensitive to timings and occasionally

the Pi might fail to get a valid reading. So check if readings are valid.

if humidity is not None and temperature is not None: print(‘Temp={0:0.1f}*C Humidity={1:0.1f}%’.format(temperature, humidity)) else: print(‘Failed to get reading. Try again!’) ```