-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathdht11.lua
More file actions
75 lines (61 loc) · 1.59 KB
/
dht11.lua
File metadata and controls
75 lines (61 loc) · 1.59 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
--------------------------------------------------------------------------------
-- DHT11 module for NODEMCU
-- LICENCE: http://opensource.org/licenses/MIT
-- zlo2k <[email protected]> from code Pigs Fly
--------------------------------------------------------------------------------
local moduleName = "dht11"
local M = {}
_G[moduleName] = M
local temp = 0
local hum = 0
local bitStream = {}
function M.init(pin)
bitStream = {}
for j = 1, 40, 1 do
bitStream[j] = 0
end
bitlength = 0
gpio.mode(pin, gpio.OUTPUT)
gpio.write(pin, gpio.LOW)
tmr.delay(20000)
--Use Markus Gritsch trick to speed up read/write on GPIO
gpio_read = gpio.read
gpio_write = gpio.write
gpio.mode(pin, gpio.INPUT)
while (gpio_read(pin) == 0) do end
c = 0
while (gpio_read(pin) == 1 and c < 100) do c = c + 1 end
while (gpio_read(pin) == 0) do end
c = 0
while (gpio_read(pin) == 1 and c < 100) do c = c + 1 end
for j = 1, 40, 1 do
while (gpio_read(pin) == 1 and bitlength < 10) do
bitlength = bitlength + 1
end
bitStream[j] = bitlength
bitlength = 0
while (gpio_read(pin) == 0) do end
end
hum = 0
temp = 0
for i = 1, 8, 1 do
if (bitStream[i + 0] > 2) then
hum = hum + 2 ^ (8 - i)
end
end
for i = 1, 8, 1 do
if (bitStream[i + 16] > 2) then
temp = temp + 2 ^ (8 - i)
end
end
bitStream = {}
gpio_read = nil
gpio_write = nil
end
function M.getTemp()
return temp
end
function M.getHumidity()
return hum
end
return M