方式1 直接读取
https://blog.csdn.net/u010900754/article/details/53078615
在连线的时候注意编码方式,注意树莓派引脚图的方向,如上图所示。我用的是三个头的dht11传感器,因此连线方式是:
VCC(或正极) --- 树莓派的3v电源
GND (地线或者负极)--- 树莓派的gnd接口
DATA (D或者out) ---树莓派的GPIO引脚
注意自己的传感器的接口的顺序。
import RPi.GPIO as GPIO import time channel =4 data = [] j = 0 GPIO.setmode(GPIO.BCM) time.sleep(1) GPIO.setup(channel, GPIO.OUT) GPIO.output(channel, GPIO.LOW) time.sleep(0.02) GPIO.output(channel, GPIO.HIGH) GPIO.setup(channel, GPIO.IN) while GPIO.input(channel) == GPIO.LOW: continue while GPIO.input(channel) == GPIO.HIGH: continue while j < 40: k = 0 while GPIO.input(channel) == GPIO.LOW: continue while GPIO.input(channel) == GPIO.HIGH: k += 1 if k > 100: break if k < 8: data.append(0) else: data.append(1) j += 1 print "sensor is working." print data humidity_bit = data[0:8] humidity_point_bit = data[8:16] temperature_bit = data[16:24] temperature_point_bit = data[24:32] check_bit = data[32:40] humidity = 0 humidity_point = 0 temperature = 0 temperature_point = 0 check = 0 for i in range(8): humidity += humidity_bit[i] * 2 ** (7-i) humidity_point += humidity_point_bit[i] * 2 ** (7-i) temperature += temperature_bit[i] * 2 ** (7-i) temperature_point += temperature_point_bit[i] * 2 ** (7-i) check += check_bit[i] * 2 ** (7-i) tmp = humidity + humidity_point + temperature + temperature_point if check == tmp: print "temperature :", temperature, "*C, humidity :", humidity, "%" else: print "wrong" print "temperature :", temperature, "*C, humidity :", humidity, "% check :", check, ", tmp :", tmp GPIO.cleanup()
这里要注意,编码方式和引脚号
(1)编码方式:PR库有两种方式,一种是bcm另一种是wiringPi的方式,两者的区别大致是bcm的的pin的序号0,1,3,。。。是与每一个gpio引脚对应的,不包含gnd和电源之类的在内,而wiringPi则是从电源开始为0,然后按增序排。使用python的脚本,只需要在setmode函数里面制定编码方式即可。
(2)引脚号:程序里面用的是bcm的4号(即channel变量),注意连线方式是否与代码匹配
方式2 间接USB读取
Arduino读取DHT11温度湿度数据
https://marshal.ohtly.com/2017/02/26/arduino-and-dht11
#include <dht.h> dht DHT; #define DHT11_PIN 7 void setup(){ Serial.begin(9600); } void loop() { int chk = DHT.read11(DHT11_PIN); Serial.print("Temperature = "); Serial.println(DHT.temperature); Serial.print("Humidity = "); Serial.println(DHT.humidity); delay(1000); }
然后上传,就可以在串口监视器中看到类似这样的信息:
Temperature = 26.00 Humidity = 32.00 Temperature = 26.00 Humidity = 32.00 Temperature = 26.00