SMART CLEO Temp humi

main.cpp

Committer:
SMART_CLEO
Date:
2017-09-28
Revision:
0:fa2b2a1e9a8f

File content as of revision 0:fa2b2a1e9a8f:

#include "mbed.h"
#include "TextLCD.h"

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

PinName pin_DHT11 = PA_15;

DigitalInOut data_pin(pin_DHT11);

// rs, rw, e, d0-d3
TextLCD lcd(PB_12, PB_13, PB_14, PB_15, PA_9, PA_10, PA_11); 

Timer tmr;

int humi;
int temp;

int dht_read(void);

int main() {
 
    lcd.printf("  Temp :     c\n");
    lcd.printf("  Humi :     %%"); 
  
    while(1) {
        if(dht_read() == 0)
        {
            lcd.locate(10, 0);
            lcd.printf("%3d", temp);
            lcd.locate(10, 1);
            lcd.printf("%3d", humi);
        }
        else
        {
            lcd.locate(10, 0);
            lcd.printf("%3d", 0);
            lcd.locate(10, 1);
            lcd.printf("%3d", 0);
        }
        wait(2);
    }
}

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_ms(18);
    data_pin.write(1);
    wait_us(10);
    data_pin.input();
    wait_us(40);

    // ACKNOWLEDGE or TIMEOUT
    unsigned long loopCnt = 10000;
    
    while(data_pin.read() == 0)if(!loopCnt--)return DHTLIB_ERROR_TIMEOUT;
 
    loopCnt = 10000;
    
    while(data_pin.read() == 1)if(!loopCnt--)return DHTLIB_ERROR_TIMEOUT;

    // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT

    for(int i=0; i<40; i++){
        
        loopCnt = 10000;
        
        while(data_pin.read() == 0)if(loopCnt-- == 0)return DHTLIB_ERROR_TIMEOUT;

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

        loopCnt = 10000;
        
        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.
    humi = bits[0]; 
    temp = bits[2]; 

    uint8_t sum = bits[0] + bits[1] + bits[2] + bits[3];
    
    if(bits[4] != sum){return DHTLIB_ERROR_CHECKSUM;}
    
    return DHTLIB_OK;
    
}