-
Notifications
You must be signed in to change notification settings - Fork 1
/
dht11.c
111 lines (97 loc) · 1.8 KB
/
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "dht11.h"
void DELAY_US(int delay) // delay for MCU running on 48 MHz
{
int i;
for (i = 0; i < delay*8; i++)
{
asm("NOP");
}
}
DHT11_ERROR_CODE_t read_DHT11(uint8_t * pData)
{
//reset DHT11
palSetPadMode(GPIOB, GPIOB_PIN2, PAL_MODE_OUTPUT_PUSHPULL);
palClearPad(GPIOB, GPIOB_PIN2);
chThdSleepMilliseconds(20);
palSetPad(GPIOB, GPIOB_PIN2);
palSetPadMode(GPIOB, GPIOB_PIN2, PAL_MODE_INPUT);
DHT11_ERROR_CODE_t errorCode = DHT11_OK;
int i = 0;
int j = 0;
int timeout = TIMEOUT_VALUE;
while(palReadPad(GPIOB, GPIOB_PIN2) == 1) /* hold on '1' */
{
if ((timeout)-- <= 0)
{
errorCode = DHT11_TIMEOUT;
break;
}
};
while(palReadPad(GPIOB, GPIOB_PIN2) == 0) /* hold on '0' */
{
if ((timeout)-- <= 0)
{
errorCode = DHT11_TIMEOUT;
break;
}
};
while(palReadPad(GPIOB, GPIOB_PIN2) == 1) /* hold on '1' */
{
if ((timeout)-- <= 0)
{
errorCode = DHT11_TIMEOUT;
break;
}
};
/* start sequence - end */
chSysLock();
/* read sequence */
if (errorCode == DHT11_OK)
{
for(j=0; j<5; j++) // bytes
{
for(i=0; i < 8; i++)
{
timeout = TIMEOUT_VALUE;
while(palReadPad(GPIOB, GPIOB_PIN2) == 0)
{
if ((timeout)-- <= 0)
{
errorCode = DHT11_TIMEOUT;
break;
}
}; /* 50 us on 0 */
if (palReadPad(GPIOB, GPIOB_PIN2) == 1)
{
DELAY_US(30);
}
pData[j] <<= 1;
if(palReadPad(GPIOB, GPIOB_PIN2) == 1)
{
DELAY_US(40); /* wait 'till 70us */
//gptPolledDelay(&GPTD3, US2ST(40));
pData[j] |= 1;
}
else
{
pData[j] &= 0xfe;
}
}
}
}
/* read sequence - end */
chSysUnlock();
/* checksum check */
if (errorCode == DHT11_OK )
{
if ((pData[0] + pData[2]) != pData[4])
{
errorCode = DHT11_WRONG_CHCKSUM;
}
else
{
errorCode = DHT11_OK;
}
}
return errorCode;
}