— SHT系列 温湿度传感器驱动
— @module sensor_sht
— @author DZQ
— @license MIT
— @copyright openLuat.com
— @release 2017.10.19
require “utils”
module(…, package.seeall)
local filename =“sensor_sht”
— 初始化并打开I2C操作
— @param I2C 内部ID
— @return number ,I2C的速率
local function i2c_open(id)
if i2c.setup(id, i2c.SLOW) ~= i2c.SLOW then
log.error(“I2C.init is: “, “fail”)
–i2c.close(id)
end
end
— 读取Sht20的温湿度
— @return int,int,第一个参数是温度,第二个是湿度(都放大了100倍,方便不适用浮点数的情况)
— @usage tmp, hum = readSht20()
function readSht20()
local id =2
i2c_open(id)
–发送指令:温度测量:0xf3,0xe3。(e:保持主机,f:非)
i2c.send(id, 0x40, 0xE3)
— sys.wait(2)
local data = i2c.recv(id, 0x40, 3)
–返回:1[高八位],2[低八位],3[CRC8效验]
local _,H,L,crc = pack.unpack(data,‘b3’)
–log.info(filename,”read data:”,TH,TL,crc)
local tmp =((4393*(H*256+L))/16384)-4685
–湿度
i2c.send(id, 0x40, 0xE5)
data = i2c.recv(id, 0x40, 3)
i2c.close(id)
_,H,L,crc = pack.unpack(data,‘b3’)
local hum =((3125*(H*256+L))/16384)-600
log.info(filename,“100*T:”,tmp,“100*H:”,hum)
return tmp,hum
end
— 读取Sht30的温湿度
— @return int,int,第一个参数是温度,第二个是湿度(都放大了100倍,方便不适用浮点数的情况)
— @usage tmp, hum = readSht30()
function readSht30()
local id =2
i2c_open(id)
–数值查询,发送指令0x2C06,通过iic发送完毕之后,sht30返回的数值是6个字节的数组
i2c.send(id, 0x44,{0x2c,0x06})
–1[温度高八位],2[温度低八位],3[温度crc校验],4[湿度高八位],5[湿度低八位],6[湿度crc校验]
local data = i2c.recv(id, 0x44, 6)
i2c.close(id)
local _,h_H,h_L,h_crc,t_H,t_L,t_crc = pack.unpack(data,‘b6’)
local tmp =((4375*(H*256+L))/16384)-4500
local hum =((2500*(H*256+L))/16384)
log.info(filename,“100*T:”,tmp,“100*H:”,hum)
return tmp,hum
end
–测试
sys.timerLoopStart(readSht20,3000)