1. 程式人生 > >樹莓派3b驅動dht11溫濕度傳感器

樹莓派3b驅動dht11溫濕度傳感器

ros tran tex his std auto div color success

  1. 新建並打開C文件

    touch dht11.c

    sudo vim dht11.c

  2. 編寫驅動程序

     1 #include<wiringPi.h>
     2 #include<stdio.h>
     3 #include<stdlib.h>
     4 #include<stdint.h>
     5 #define MAX_TIME 85
     6 #define DHT11PIN 7
     7 #define ATTEMPTS 5                 //retry 5 times when no response
     8 int dht11_val[5
    ]={0,0,0,0,0}; 9 10 int dht11_read_val(){ 11 uint8_t lststate=HIGH; //last state 12 uint8_t counter=0; 13 uint8_t j=0,i; 14 for(i=0;i<5;i++) 15 dht11_val[i]=0; 16 17 //host send start signal 18 pinMode(DHT11PIN,OUTPUT); //set pin to output 19 digitalWrite(DHT11PIN,LOW); //
    set to low at least 18ms 20 delay(18); 21 digitalWrite(DHT11PIN,HIGH); //set to high 20-40us 22 delayMicroseconds(40); 23 24 //start recieve dht response 25 pinMode(DHT11PIN,INPUT); //set pin to input 26 for(i=0;i<MAX_TIME;i++) 27 { 28 counter=0; 29 while
    (digitalRead(DHT11PIN)==lststate){ //read pin state to see if dht responsed. if dht always high for 255 + 1 times, break this while circle 30 counter++; 31 delayMicroseconds(1); 32 if(counter==255) 33 break; 34 } 35 lststate=digitalRead(DHT11PIN); //read current state and store as last state. 36 if(counter==255) //if dht always high for 255 + 1 times, break this for circle 37 break; 38 // top 3 transistions are ignored, maybe aim to wait for dht finish response signal 39 if((i>=4)&&(i%2==0)){ 40 dht11_val[j/8]<<=1; //write 1 bit to 0 by moving left (auto add 0) 41 if(counter>16) //long mean 1 42 dht11_val[j/8]|=1; //write 1 bit to 1 43 j++; 44 } 45 } 46 // verify checksum and print the verified data 47 if((j>=40)&&(dht11_val[4]==((dht11_val[0]+dht11_val[1]+dht11_val[2]+dht11_val[3])& 0xFF))){ 48 printf("RH:%d,TEMP:%d\n",dht11_val[0],dht11_val[2]); 49 return 1; 50 } 51 else 52 return 0; 53 } 54 55 int main(void){ 56 int attempts=ATTEMPTS; 57 if(wiringPiSetup()==-1) 58 exit(1); 59 while(attempts){ //you have 5 times to retry 60 int success = dht11_read_val(); //get result including printing out 61 if (success) { //if get result, quit program; if not, retry 5 times then quit 62 break; 63 } 64 attempts--; 65 delay(2500); 66 } 67 return 0; 68 }

    按esc,然後輸入:wq保存退出。

  3. 編譯c文件

    需安裝wiringPi開發庫,安裝教程詳見本博主博客:樹莓派安裝wiringPi開發庫

    輸入命令:

    gcc -Wall -o dht11 dht11.c -lwiringPi

    1

    gcc是編譯器,-Wall是在編譯時顯示警告信息,-o dht11.c是將dht11.c文件編譯成文件名為dht11的可執行文件,-lwiringPi是將wiringPi頭文件包含在可執行文件中。

  4. 運行程序

    輸入命令:

    sudo ./dht11

    技術分享

    可以看到濕度和溫度值都正確的打印在了屏幕上。

樹莓派3b驅動dht11溫濕度傳感器