-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdht_api.c
101 lines (85 loc) · 1.93 KB
/
dht_api.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
93
94
95
96
97
98
99
100
#include <stdint.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdlib.h>
#include "farm_api.h"
#include "dht_api.h"
#define MAXTIMINGS 85
int dht11_dat[5] = { 0, 0, 0, 0, 0 };
struct dht_data DHT_get_data(int farm_fd)
{
uint8_t laststate = 1;
uint8_t counter = 0;
uint8_t j = 0, i;
float f; /* fahrenheit */
struct dht_data data;
dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
/* pull pin down for 18 milliseconds */
DHT_set_output(farm_fd);
DHT_off(farm_fd);
sleepm(18);
/* then pull it up for 40 microseconds */
DHT_on(farm_fd);
sleepu( 40 );
/* prepare to read the pin */
DHT_set_input(farm_fd);
/* detect change and read data */
for ( i = 0; i < MAXTIMINGS; i++ )
{
counter = 0;
while ( DHT_read_data(farm_fd) == laststate )
{
counter++;
sleepu( 1 );
if ( counter == 255 )
{
break;
}
}
laststate = DHT_read_data(farm_fd);
if ( counter == 255 )
break;
/* ignore first 3 transitions */
if ( (i >= 4) && (i % 2 == 0) )
{
/* shove each bit into the storage bytes */
dht11_dat[j / 8] <<= 1;
if ( counter > 16 )
dht11_dat[j / 8] |= 1;
j++;
}
}
/*
* check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
* print it out if data is good
*/
if ( (j >= 40) &&
(dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ) {
data.humidity = dht11_dat[0];
data.temperature = dht11_dat[2];
} else {
data.humidity = 0;
data.temperature = 0;
}
return data;
}
void DHT_set_input(int farm_fd) {
ioctl(farm_fd, DHT_SET_INPUT, 0);
}
void DHT_set_output(int farm_fd) {
ioctl(farm_fd, DHT_SET_OUTPUT, 0);
}
int DHT_read_data(int farm_fd) {
int value = 0;
ioctl(farm_fd, DHT_GET_DATA, &value);
return value;
}
void DHT_on(int farm_fd) {
ioctl(farm_fd, DHT_ON, 0);
}
void DHT_off(int farm_fd) {
ioctl(farm_fd, DHT_OFF, 0);
}