PageRenderTime 46ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/DHT11.c

https://bitbucket.org/arturmietek/avr-starter
C | 71 lines | 49 code | 9 blank | 13 comment | 14 complexity | 8dd064127b973e81c68560626115cd63 MD5 | raw file
  1. /*
  2. * DHT11.c
  3. *
  4. * Created on: 02-01-2013
  5. * Author: mentos
  6. */
  7. #include <stdlib.h>
  8. #include <avr/io.h>
  9. #include <util/delay.h>
  10. #include "DHT11.h"
  11. uint8_t DHT11_GetData(uint8_t select) {
  12. uint8_t bits[5];
  13. uint8_t i, j = 0;
  14. //reset port
  15. DHT11_DDR |= (1 << DHT11_INPUTPIN); //output
  16. DHT11_PORT |= (1 << DHT11_INPUTPIN); //high
  17. _delay_ms(100);
  18. //send request
  19. DHT11_PORT &= ~(1 << DHT11_INPUTPIN); //low
  20. _delay_ms(18);
  21. DHT11_PORT |= (1 << DHT11_INPUTPIN); //high
  22. _delay_us(1);
  23. DHT11_DDR &= ~(1 << DHT11_INPUTPIN); //input
  24. _delay_us(39);
  25. //check start condition 1
  26. if ((DHT11_PIN & (1 << DHT11_INPUTPIN))) {
  27. return DHT11_ERROR;
  28. }
  29. _delay_us(80);
  30. //check start condition 2
  31. if (!(DHT11_PIN & (1 << DHT11_INPUTPIN))) {
  32. return DHT11_ERROR;
  33. }
  34. _delay_us(80);
  35. //read the data
  36. for (j = 0; j < 5; j++) { //read 5 byte
  37. uint8_t result = 0;
  38. for (i = 0; i < 8; i++) { //read every bit
  39. while (!(DHT11_PIN & (1 << DHT11_INPUTPIN)))
  40. ; //wait for an high input
  41. _delay_us(30);
  42. if (DHT11_PIN & (1 << DHT11_INPUTPIN)) //if input is high after 30 us, get result
  43. result |= (1 << (7 - i));
  44. while (DHT11_PIN & (1 << DHT11_INPUTPIN))
  45. ; //wait until input get low
  46. }
  47. bits[j] = result;
  48. }
  49. //reset port
  50. DHT11_DDR |= (1 << DHT11_INPUTPIN); //output
  51. DHT11_PORT |= (1 << DHT11_INPUTPIN); //low
  52. _delay_ms(100);
  53. //check checksum
  54. if (bits[0] + bits[1] + bits[2] + bits[3] == bits[4]) {
  55. if (select == DHT11_DATA_TEMPERATURE) { //return temperature
  56. return (bits[2]);
  57. } else if (select == DHT11_DATA_HUMIDITY) { //return humidity
  58. return (bits[0]);
  59. }
  60. }
  61. return DHT11_ERROR;
  62. }