Saturday, March 21, 2015

DHT11 Digital Humidity and Temperature Sensor MikroC Library

DHT11 mikroc library
I have finished writing a MikroC library for the DHT11 sensor, and from now interfacing this sensor will be very easy. This library has just one command which is DHT11_Read(); .
This command generates a 16-bit number, the first 8 bits are for humidity and the last 8 bits are for temperature. For example if a received number is 0011010000011011 (Ox341B), this means that the first 8-bit number equals to 52 which is for humidity and the last 8-bit number equals to 27 which is for temperature.
If the received number is 0x6363 this means that there is no response from the sensor and the connection between the sensor and the microcontroller should be verified.
If the received number is 0x5858 which means there are some errors with results and there is a checksum error. 
The library can be downloaded from the following link:
How to install this library:
The following link from MikroElectronika website shows how to install libraries into the compiler.
 http://www.mikroe.com/package-manager/
Or watch the following video:

 
Example:
This example shows how to interface the DHT11 with Microchip PIC18F4550 using DHT11 library.
The following picture shows circuit schematic:
dht11 sensor mikroc library pic18f4550

MikroC Code:


 // LCD module connections
sbit LCD_RS at RB5_bit;
sbit LCD_EN at RB4_bit;
sbit LCD_D4 at RB3_bit;
sbit LCD_D5 at RB2_bit;
sbit LCD_D6 at RB1_bit;
sbit LCD_D7 at RB0_bit;
sbit LCD_RS_Direction at TRISB5_bit;
sbit LCD_EN_Direction at TRISB4_bit;
sbit LCD_D4_Direction at TRISB3_bit;
sbit LCD_D5_Direction at TRISB2_bit;
sbit LCD_D6_Direction at TRISB1_bit;
sbit LCD_D7_Direction at TRISB0_bit;
// End LCD module connections

 // DHT11 sensor connections
sbit DHT11_Pin at RD0_bit;
sbit DHT11_Pin_Direction at TRISD0_bit;
 // End DHT11 sensor connections
 
 unsigned short  Temperature, Humidity ;
 unsigned value ;

void main() {
 OSCCON =  0X70;       // Set internal oscillator at 8MHz
 ADCON1 = 0x0F;        // Configure AN pins as digital
 Lcd_Init();
 Lcd_Cmd(_LCD_CURSOR_OFF);        // cursor off
 Lcd_Cmd(_LCD_CLEAR);            // clear LCD
 while(1){
  value  = DHT11_Read();
  if (value == 0x6363){
   Lcd_Out(1, 1, "  No response  ");
  Lcd_Out(2, 1, "from the sensor");
  }
  if (value == 0x5858){
   Lcd_Cmd(_LCD_CLEAR);
   Lcd_Out(1, 1, "Check sum error");
  }
  if ((value != 0x6363) && (value != 0x5858)) {
  Temperature = value & 0xFF;
  Humidity = value >> 8;
  Lcd_Out(1, 1, "     Temp:   C ");
  Lcd_Out(2, 1, " Humidity:   % ");
  LCD_Chr(1, 12, 48 + ((Temperature / 10) % 10));
  LCD_Chr(1, 13, 48 + (Temperature % 10));
  LCD_Chr(2, 12, 48 + ((Humidity / 10) % 10));
  LCD_Chr(2, 13, 48 + (Humidity % 10));
  }
  delay_ms(1000);
  }
}