樹莓派驅動DHT11模塊

1.新建並打開C文件

touch dht11.c
sudo vim dht11.c

2.編寫驅動程序

以下是我在其他博客上看到的一份代碼,借鑑的國外程序員編寫的驅動程序

#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAX_TIME 85
#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(40);

    //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))){
        printf("RH:%d,TEMP:%d\n",dht11_val[0],dht11_val[2]);
        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;
}

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

3.編譯c文件
需安裝wiringPi開發庫,安裝教程詳見本博主博客:樹莓派安裝wiringPi開發庫
輸入命令:

gcc -Wall -o dht11 dht11.c -lwiringPi

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

4.運行程序
輸入命令:
sudo ./dht11

這裏寫圖片描述

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

發佈了39 篇原創文章 · 獲贊 303 · 訪問量 40萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章