GSOE Webserver ESP01 DHT11

Dependencies:   LCD_i2c_GSOE ESP8266WebserverGSOE

main.cpp

Committer:
jack1930
Date:
2021-07-26
Revision:
1:e6f838f99eeb
Parent:
0:8fe7d36af056
Child:
2:85f2573de3e4

File content as of revision 1:e6f838f99eeb:


#include "mbed.h"
#include "LCD.h"



#define DHTLIB_OK                0
#define DHTLIB_ERROR_CHECKSUM   -1
#define DHTLIB_ERROR_TIMEOUT    -2

Timer tmr;
lcd mylcd;

DigitalInOut data_pin(PB_15);

int humidity;
int temperature;

//########################################
// DHT11 Library
//########################################
int dht_read(void){
    
    // BUFFER TO RECEIVE
    uint8_t bits[5];
    uint8_t cnt = 7;
    uint8_t idx = 0;
    
    tmr.stop();
    tmr.reset();

    // EMPTY BUFFER
    for(int i=0; i< 5; i++) bits[i] = 0;

    // REQUEST SAMPLE
    data_pin.output();
    data_pin.write(0);
    wait_us(18000);
    data_pin.write(1);
    wait_us(40);
    data_pin.input();

    // ACKNOWLEDGE or TIMEOUT
    unsigned int loopCnt = 20000;
    
    while(!data_pin.read())if(!loopCnt--)return DHTLIB_ERROR_TIMEOUT;

    loopCnt = 20000;
    
    while(data_pin.read())if(!loopCnt--)return DHTLIB_ERROR_TIMEOUT;

    // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
    for(int i=0; i<40; i++){
        
        loopCnt = 20000;
        
        while(!data_pin.read())if(loopCnt-- == 0)return DHTLIB_ERROR_TIMEOUT;

        //unsigned long t = micros();
        tmr.start();

        loopCnt = 20000;
        
        while(data_pin.read())if(!loopCnt--)return DHTLIB_ERROR_TIMEOUT;

        if(tmr.read_us() > 40) bits[idx] |= (1 << cnt);
        
        tmr.stop();
        tmr.reset();
        
        if(cnt == 0){   // next byte?
        
            cnt = 7;    // restart at MSB
            idx++;      // next byte!
            
        }else cnt--;
        
    }

    // WRITE TO RIGHT VARS
    // as bits[1] and bits[3] are allways zero they are omitted in formulas.
    humidity    = bits[0]; 
    temperature = bits[2]; 

    uint8_t sum = bits[0] + bits[2];  

    if(bits[4] != sum)return DHTLIB_ERROR_CHECKSUM;
    
    return DHTLIB_OK;
    
}

char buffer[17];

//########################################
// End of DHT11 Library
//########################################

int main(void){
    
    mylcd.clear();
    mylcd.cursorpos(0);
    
    mylcd.printf("Nucleo - DHT11");
    
    for(;;){
       int fehler=dht_read();
        
            

            mylcd.cursorpos(0x40);
            mylcd.printf("Hum %2d%%  Tmp %2dc  ", humidity, temperature);
            wait_us(500000);
            

    
    }
    
}