Guest User

DHT11 test Raspberry Pi

a guest
Oct 26th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. /*
  2. * dht11.c:
  3. * Simple test program to test the wiringPi functions
  4. * DHT11 test
  5. */
  6.  
  7. #include <wiringPi.h>
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <stdint.h>
  12. #define MAXTIMINGS 85
  13. #define DHTPIN 7
  14. int dht11_dat[5] = { 0, 0, 0, 0, 0 };
  15.  
  16. void read_dht11_dat()
  17. {
  18. uint8_t laststate = HIGH;
  19. uint8_t counter = 0;
  20. uint8_t j = 0, i;
  21. float f; /* fahrenheit */
  22.  
  23. dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
  24.  
  25. /* pull pin down for 18 milliseconds */
  26. pinMode( DHTPIN, OUTPUT );
  27. digitalWrite( DHTPIN, LOW );
  28. delay( 18 );
  29. /* then pull it up for 40 microseconds */
  30. digitalWrite( DHTPIN, HIGH );
  31. delayMicroseconds( 40 );
  32. /* prepare to read the pin */
  33. pinMode( DHTPIN, INPUT );
  34.  
  35. /* detect change and read data */
  36. for ( i = 0; i < MAXTIMINGS; i++ )
  37. {
  38. counter = 0;
  39. while ( digitalRead( DHTPIN ) == laststate )
  40. {
  41. counter++;
  42. delayMicroseconds( 1 );
  43. if ( counter == 255 )
  44. {
  45. break;
  46. }
  47. }
  48. laststate = digitalRead( DHTPIN );
  49.  
  50. if ( counter == 255 )
  51. break;
  52.  
  53. /* ignore first 3 transitions */
  54. if ( (i >= 4) && (i % 2 == 0) )
  55. {
  56. /* shove each bit into the storage bytes */
  57. dht11_dat[j / 8] <<= 1;
  58. if ( counter > 16 )
  59. dht11_dat[j / 8] |= 1;
  60. j++;
  61. }
  62. }
  63.  
  64. /*
  65. * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
  66. * print it out if data is good
  67. */
  68. if ( (j >= 40) &&
  69. (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) )
  70. {
  71. f = dht11_dat[2] * 9. / 5. + 32;
  72. printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n",
  73. dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
  74. }else {
  75. printf( "Data not good, skip\n" );
  76. }
  77. }
  78.  
  79. int main( void )
  80. {
  81. printf( "Raspberry Pi wiringPi DHT11 Temperature test program\n" );
  82.  
  83. if ( wiringPiSetup() == -1 )
  84. exit( 1 );
  85.  
  86. while ( 1 )
  87. {
  88. read_dht11_dat();
  89. delay( 1000 ); /* wait 1sec to refresh */
  90. }
  91.  
  92. return(0);
  93. }
Add Comment
Please, Sign In to add comment