您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“樹莓派如何實現(xiàn)溫濕度傳感器DHT11”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“樹莓派如何實現(xiàn)溫濕度傳感器DHT11”這篇文章吧。
1、連線
我買的這個DHT11比較郁悶,三根管腳,沒有注明哪個是VCC,哪個是GND,網(wǎng)上搜了一堆,為毛別的傳感器都標注清楚了,我的只標注了個正負號,后來跟某寶老板咨詢了下,確定是+是VCC,-是GND,中間的是Data(或許是因為我是電信專業(yè)的小白,不懂這些行話)
1–>3.3v 接左邊第1個GPIO針腳
2–>GPIO 數(shù)據(jù)接口,可隨意連接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 //讀取數(shù)據(jù)引腳 #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模塊的度出來的就是溫濕度值,不需要轉換,網(wǎng)上其他人給的代碼還轉換了下,不清楚原因。
編譯:
gcc testDHT11.c -o test -lwiringPi
運行
sudo ./test
注意,要使用root權限才能正常運行。
以上是“樹莓派如何實現(xiàn)溫濕度傳感器DHT11”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。