-
Notifications
You must be signed in to change notification settings - Fork 0
/
esp32-dht11.c
92 lines (76 loc) · 2.12 KB
/
esp32-dht11.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "esp32-dht11.h"
int wait_for_state(dht11_t dht11,int state,int timeout)
{
gpio_set_direction(dht11.dht11_pin, GPIO_MODE_INPUT);
int count = 0;
while(gpio_get_level(dht11.dht11_pin) != state)
{
if(count == timeout) return -1;
count += 2;
ets_delay_us(2);
}
return count;
}
void hold_low(dht11_t dht11,int hold_time_us)
{
gpio_set_direction(dht11.dht11_pin,GPIO_MODE_OUTPUT);
gpio_set_level(dht11.dht11_pin,0);
ets_delay_us(hold_time_us);
gpio_set_level(dht11.dht11_pin,1);
}
int dht11_read(dht11_t *dht11,int connection_timeout)
{
int waited = 0;
int one_duration = 0;
int zero_duration = 0;
int timeout_counter = 0;
uint8_t recieved_data[5] =
{
0x00,
0x00,
0x00,
0x00,
0x00
};
while(timeout_counter < connection_timeout)
{
timeout_counter++;
gpio_set_direction(dht11->dht11_pin,GPIO_MODE_INPUT);
hold_low(*dht11, 18000);
waited = wait_for_state(*dht11,0,40);
if(waited == -1)
{
ESP_LOGE("DHT11:","Failed at phase 1");
ets_delay_us(20000);
continue;
}
waited = wait_for_state(*dht11,1,80);
if(waited == -1)
{
ESP_LOGE("DHT11:","Failed at phase 2");
ets_delay_us(20000);
continue;
}
waited = wait_for_state(*dht11,0,80);
if(waited == -1)
{
ESP_LOGE("DHT11:","Failed at phase 3");
ets_delay_us(20000);
continue;
}
break;
}
if(timeout_counter == connection_timeout) return -1;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 8; j++)
{
zero_duration = wait_for_state(*dht11,1,60);
one_duration = wait_for_state(*dht11,0,80);
recieved_data[i] |= (one_duration > zero_duration) << (7 - j);
}
}
dht11->humidity = recieved_data[0] + recieved_data[1] /10.0 ;
dht11->temperature = recieved_data[2] + recieved_data[3] /10.0 ;
return 0;
}