Introduction

In this lesson, we’ll introduce how to use Raspberry Pi to get data from DHT11 Temperature and humidity sensor module .

Hardware Preparation
1 * Raspberry Pi
1 * Breadboard
1 * DHT11
Jumper wires
1 * T-Extension Board with 40-Pin Cable(Optional)

Software Preparation
Note: In this lesson, we remotely control raspberry pi via PuTTy on PC. To learn how to config raspberry pi, please visit lesson 1: getting started with raspberry pi.

Experimental Principle
DHT11 module is a temperature and humidity sensor which has 3 pins: VCC, GND and DATA. This module adopts OneWire protocol to communicate. At the beginning of communication process, DATA pin sends signal to DHT11, and then DHT11 receives the signal and sends answer signal to host, at last, the host receives answer signal and starts to receive 40 bit Temperature and humidity. (8 bit integer part of humidity + 8 bit decimal part of humidity + 8 bit integer part of temperature + 8 bit decimal part of  temperature + 8 bit checksum)

Schematic diagram of DHT11

Schematic diagram of DHT11 with raspberry

B14 for in above graph means BCM GPIO#14(TXD) or Physical pin#8 or wiringPi#15
Note: B means BCM(Broadcom pin number). If you don’t know what is BCM pin#, Physical pin#, wiringPi#, please review our lesson 3: Introduction Of Raspberry Pi GPIOLearn more about GPIO of raspberry pi, please review our lesson 2: Introduction Of Raspberry Pi GPIO

Connection Graph

Software

We’ll provide two kinds of codes for C language users and Python language users.

For C language users,please take following steps:


Note: please make sure you have installated wiringpi library. Click here, you can learn more about  wiringpi installation.
Step 1) Download sample code dht11.c from osoyoo.com by typing following commands in terminal:

cd ~

wget http://osoyoo.com/driver/pi3_start_learning_kit_lesson_17/dht11.c

Note:
If you want to customize the sample code file , you can use nano editor to edit source code by typing following command in terminal:
sudo  nano dht11.c

3) Compile code

gcc -Wall -o dht11 dht11.c -lwiringPi

4) Run the program

sudo ./dht11

5) Program result

Once the program starts running, the terminal will show real temperature and humidity again and again.

C language Sample Code and Explanation comments

dht11.c
 
  1. #include
  2. #include
  3. #include
  4. #include
  5. #include
  6. #include
  7. #define MAXTIMINGS 85
  8. #define DHTPIN 15 //DHT connect to TxD
  9. int dht11_dat[5] ={0,0,0,0,0};//store DHT11 data
  10. void read_dht11_dat()
  11. {
  12. uint8_t laststate = HIGH;
  13. uint8_t counter = 0;
  14. uint8_t j = 0,i;
  15. float f;//fahrenheit
  16. dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
  17. //pull pin down to send start signal
  18. pinMode( DHTPIN, OUTPUT );
  19. digitalWrite( DHTPIN, LOW );
  20. delay( 18 );
  21. //pull pin up and wait for sensor response
  22. digitalWrite( DHTPIN, HIGH );
  23. delayMicroseconds( 40 );
  24. //prepare to read the pin
  25. pinMode( DHTPIN, INPUT );
  26. //detect change and read data
  27. for ( i = 0; i < MAXTIMINGS; i++ ) { counter = 0; while ( digitalRead( DHTPIN ) == laststate ) { counter++; delayMicroseconds( 1 ); if ( counter == 255 ) { break; } } laststate = digitalRead( DHTPIN ); if ( counter == 255 ) break; //ignore first 3 transitions if ( (i >= 4) && (i % 2 == 0) )
  28. {
  29. //shove each bit into the storage bytes
  30. dht11_dat[j / 8]
  31. dht11_dat[j / 8] |= 1;
  32. j++;
  33. }
  34. }
  35. //check we read 40 bits(8bit x 5) +verify checksum in the last byte
  36. //print it out if data is good
  37. if ( (j >= 40) &&
  38. (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) )
  39. {
  40. f = dht11_dat[2] * 9. / 5. + 32;
  41. printf( "Humidity = %d.%d %% Temperature = %d.%d C (%.1f F)\n",
  42. dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
  43. }
  44. else
  45. {
  46. printf( "Data not good, skip\n" );
  47. }
  48. }
  49. void print_info()
  50. {
  51. printf("\n");
  52. printf("|***************************|\n");
  53. printf("| DHT11 test |\n");
  54. printf("| --------------------------|\n");
  55. printf("| DHT11 connect to GPIO14 |\n");
  56. printf("| --------------------------|\n");
  57. printf("| OSOYOO|\n");
  58. printf("|***************************|\n");
  59. printf("Program is running...\n");
  60. printf("Press Ctrl+C to end the program\n");
  61. }
  62. int main( void )
  63. {
  64. if ( wiringPiSetup() == -1 )
  65. {
  66. fprintf(stderr,"Can't init wiringPi: %s\n",strerror(errno));
  67. exit(EXIT_FAILURE);
  68. }
  69. print_info();
  70. while ( 1 )
  71. {
  72. read_dht11_dat();
  73. delay(1000);//wait ls to refresh
  74. }
  75. return(0);
  76. }

For python users


When programming with Python language , normally we use GPIO library called RPi.GPIO which comes with Rasbian Jessie OS. Click here, you can learn more about RPI.GPIO and Python.

1)  Download sample python code to /home/pi by following terminal command:

cd ~

wget http://osoyoo.com/driver/pi3_start_learning_kit_lesson_17/dht11.py

Note:
If you want to customize the sample code file , you can use nano editor to edit source code by typing following command in terminal:

sudo nano dht11.py

3) Run program

sudo python ./dht11.py

4) Program result

Once the program starts running , the terminal will show real temperature and humidity again and again.

Python sample code Analysis:

dht11.py
 
  1. import RPi.GPIO as GPIO
  2. import time
  3. #DHT11 connect to BCM_GPIO14
  4. DHTPIN = 14
  5. GPIO.setmode(GPIO.BCM)
  6. MAX_UNCHANGE_COUNT = 100
  7. STATE_INIT_PULL_DOWN = 1
  8. STATE_INIT_PULL_UP = 2
  9. STATE_DATA_FIRST_PULL_DOWN = 3
  10. STATE_DATA_PULL_UP = 4
  11. STATE_DATA_PULL_DOWN = 5
  12. def read_dht11_dat():
  13. GPIO.setup(DHTPIN, GPIO.OUT)
  14. GPIO.output(DHTPIN, GPIO.HIGH)
  15. time.sleep(0.05)
  16. GPIO.output(DHTPIN, GPIO.LOW)
  17. time.sleep(0.02)
  18. GPIO.setup(DHTPIN, GPIO.IN, GPIO.PUD_UP)
  19. unchanged_count = 0
  20. last = -1
  21. data = []
  22. while True:
  23. current = GPIO.input(DHTPIN)
  24. data.append(current)
  25. if last != current:
  26. unchanged_count = 0
  27. last = current
  28. else:
  29. unchanged_count += 1
  30. if unchanged_count > MAX_UNCHANGE_COUNT:
  31. break
  32. state = STATE_INIT_PULL_DOWN
  33. lengths = []
  34. current_length = 0
  35. for current in data:
  36. current_length += 1
  37. if state == STATE_INIT_PULL_DOWN:
  38. if current == GPIO.LOW:
  39. state = STATE_INIT_PULL_UP
  40. else:
  41. continue
  42. if state == STATE_INIT_PULL_UP:
  43. if current == GPIO.HIGH:
  44. state = STATE_DATA_FIRST_PULL_DOWN
  45. else:
  46. continue
  47. if state == STATE_DATA_FIRST_PULL_DOWN:
  48. if current == GPIO.LOW:
  49. state = STATE_DATA_PULL_UP
  50. else:
  51. continue
  52. if state == STATE_DATA_PULL_UP:
  53. if current == GPIO.HIGH:
  54. current_length = 0
  55. state = STATE_DATA_PULL_DOWN
  56. else:
  57. continue
  58. if state == STATE_DATA_PULL_DOWN:
  59. if current == GPIO.LOW:
  60. lengths.append(current_length)
  61. state = STATE_DATA_PULL_UP
  62. else:
  63. continue
  64. if len(lengths) != 40:
  65. print "Data not good, skip"
  66. return False
  67. shortest_pull_up = min(lengths)
  68. longest_pull_up = max(lengths)
  69. halfway = (longest_pull_up + shortest_pull_up) / 2
  70. bits = []
  71. the_bytes = []
  72. byte = 0
  73. for length in lengths:
  74. bit = 0
  75. if length > halfway:
  76. bit = 1
  77. bits.append(bit)
  78. print "bits: %s, length: %d" % (bits, len(bits))
  79. for i in range(0, len(bits)):
  80. byte = byte
  81. if (bits[i]):
  82. byte = byte | 1
  83. else:
  84. byte = byte | 0
  85. if ((i + 1) % 8 == 0):
  86. the_bytes.append(byte)
  87. byte = 0
  88. print the_bytes
  89. checksum = (the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3]) & 0xFF
  90. if the_bytes[4] != checksum:
  91. print "Data not good, skip"
  92. return False
  93. return the_bytes[0], the_bytes[2]
  94. def main():
  95. print "Raspberry Pi wiringPi DHT11 Temperature test program\n"
  96. while True:
  97. result = read_dht11_dat()
  98. if result:
  99. humidity, temperature = result
  100. print "humidity: %s %%, Temperature: %s C" % (humidity, temperature)
  101. time.sleep(1)
  102. def destroy():
  103. GPIO.cleanup()
  104. if __name__ == '__main__':
  105. try:
  106. main()
  107. except KeyboardInterrupt:
  108. destroy()

Leave a Reply

WordPress spam blocked by CleanTalk.
Bombax Theme designed by itx
"