-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDHT11.c
More file actions
77 lines (63 loc) · 2.23 KB
/
DHT11.c
File metadata and controls
77 lines (63 loc) · 2.23 KB
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
#include <string.h>
#include <wiringPi.h>
#include <stdlib.h>
#include "DHT11.h"
int* readDHT(int dhtpin){
int* dht_data = malloc(5*sizeof(int)); // Initialize array to store the data
memset(dht_data, 0, 5*sizeof(int));
int bit_position = 7; //start at highest bit
int byte_position = 0;
pinMode(dhtpin, OUTPUT);
digitalWrite(dhtpin, LOW); //MCU START SIGNAL
delay(18);//start signal must last at least 18 ms for DHT to notice
digitalWrite(dhtpin, HIGH); //set high and wait for response
delayMicroseconds(40); //wait for response
pinMode(dhtpin, INPUT);//DHT pulls data pin to low
//DHT pulls to low for 80us and up for 80us
while(digitalRead(dhtpin) == LOW){
delayMicroseconds(1);
}
while(digitalRead(dhtpin) == HIGH){
delayMicroseconds(1);
}
//transmission start
for(int i = 0; i < 40; i++){ //read 40 bits
while(digitalRead(dhtpin) == LOW){//delay until high
delayMicroseconds(1);
}
int counter = 0;
while(digitalRead(dhtpin) == HIGH){//count how long pin is high, 27 microseconds means 0, 70 microseconds means 1
delayMicroseconds(1);
counter++;
if(counter > 80){
return NULL; //something went horribly wrong, skip
}
}
if(counter >= 30){//if higher than 30, assume its 1
int bit = 1<<bit_position; //we gotta left-shift the bit by 7 decreasing because we are working with MSB first
dht_data[byte_position] |= bit;
bit_position--;
}
else{ //else its 0
bit_position--;//0 we aint gotta do SHIT
}
if(bit_position < 0){
bit_position = 7;
byte_position++;
}
int tempCount = 0;
while(digitalRead(dhtpin) == HIGH){ //wait until low again
delayMicroseconds(1);
tempCount++;
if(tempCount > 100){
return NULL; //something went horribly wrong, skip
}
}
}
if((dht_data[4] == ( (dht_data[0] + dht_data[1] + dht_data[2] + dht_data[3]) & 0xFF) )){
return dht_data;
}
else{
return NULL;
}
}