您好,登录后才能下订单哦!
这篇文章主要为大家展示了“树莓派如何实现温湿度传感器DHT11”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“树莓派如何实现温湿度传感器DHT11”这篇文章吧。
1、连线
我买的这个DHT11比较郁闷,三根管脚,没有注明哪个是VCC,哪个是GND,网上搜了一堆,为毛别的传感器都标注清楚了,我的只标注了个正负号,后来跟某宝老板咨询了下,确定是+是VCC,-是GND,中间的是Data(或许是因为我是电信专业的小白,不懂这些行话)
1–>3.3v 接左边第1个GPIO针脚
2–>GPIO 数据接口,可随意连接1个GPIO针脚(第7个针脚对应的是GPIO Pin #4,和下面的代码对应)
3–>GND 接地(第6个针脚或其他GND)
2、安装gpio驱动(姑且叫驱动吧,原理还不清楚)
sudo apt-get install wiringpi
3、运行例子(C代码)
#include <wiringPi.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #define MAX_TIME 100 #define DHT11PIN 7 //读取数据引脚 #define ATTEMPTS 5 //retry 5 times when no response int dht11_val[5]={0,0,0,0,0}; int dht11_read_val(){ uint8_t lststate=HIGH; //last state uint8_t counter=0; uint8_t j=0,i; for(i=0;i<5;i++) dht11_val[i]=0; //host send start signal pinMode(DHT11PIN,OUTPUT); //set pin to output digitalWrite(DHT11PIN,LOW); //set to low at least 18ms delay(18); digitalWrite(DHT11PIN,HIGH); //set to high 20-40us delayMicroseconds(30); //start recieve dht response pinMode(DHT11PIN,INPUT); //set pin to input for(i=0;i<MAX_TIME;i++) { counter=0; while(digitalRead(DHT11PIN)==lststate){ //read pin state to see if dht responsed. if dht always high for 255 + 1 times, break this while circle counter++; delayMicroseconds(1); if(counter==255) break; } lststate=digitalRead(DHT11PIN); //read current state and store as last state. if(counter==255) //if dht always high for 255 + 1 times, break this for circle break; // top 3 transistions are ignored, maybe aim to wait for dht finish response signal if((i>=4)&&(i%2==0)){ dht11_val[j/8]<<=1; //write 1 bit to 0 by moving left (auto add 0) if(counter>16) //long mean 1 dht11_val[j/8]|=1; //write 1 bit to 1 j++; } } // verify checksum and print the verified data if((j>=40)&&(dht11_val[4]==((dht11_val[0]+dht11_val[1]+dht11_val[2]+dht11_val[3])& 0xFF))){ float f, h; h = dht11_val[0] + dht11_val[1]; f = dht11_val[2] + dht11_val[3]; printf("Temp = %.1f *C, Hum = %.1f \%\n", f, h); return 1; } else return 0; } int main(void){ int attempts=ATTEMPTS; if(wiringPiSetup()==-1) exit(1); while(attempts){ //you have 5 times to retry int success = dht11_read_val(); //get result including printing out if (success) { //if get result, quit program; if not, retry 5 times then quit break; } attempts--; delay(2500); } return 0; }
注意第48,49行,针对DHT11模块的度出来的就是温湿度值,不需要转换,网上其他人给的代码还转换了下,不清楚原因。
编译:
gcc testDHT11.c -o test -lwiringPi
运行
sudo ./test
注意,要使用root权限才能正常运行。
以上是“树莓派如何实现温湿度传感器DHT11”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。