读取DHT12的温湿度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-- 初始化并打开I2C操作DHT12
local function read_dht12(id)
if i2c.setup(id, i2c.SLOW) ~= i2c.SLOW then
log.error("I2C.init is: ", "fail")
i2c.close(id)
return
end
i2c.send(id, 0x5C, 0x00)
local data = i2c.recv(id, 0x5C, 5)
i2c.close(id)
log.info("DHT12 HEX data: ", data:toHex())
-- 分别是湿度整数,湿度小数,温度整数,温度湿度
local _, h_H, h_L, t_H, t_L = pack.unpack(data, 'b4')
log.info("DHT12 data: ", h_H, h_L, t_H, t_L)
-- 需要考虑温度低于0度的情况, t_L第0位是符号位
local t_L2 = tonumber(t_L)
if t_L2 > 127 then
return h_H .. ".".. h_L, "-" .. t_H .. "." .. tostring(t_L2 - 128)
else
return h_H .. ".".. h_L, t_H .. "." .. t_L
end
end

上次更新 2021-01-28