I2C设备
# 简介
Air722UG模块提供2个I2C接口,速率支持FAST(400KHz)、SLOW(100KHz)、3500KHz。外设地址支持0x00-0x7f。其中AT版本并不支持I2C操作,只能在LuatOS-Air二次开发方式使用。
-- ---
# iic接口控制
iic库由底层core实现,相关API接口如下:
|iic接口| 描述|
| --- | --- |
| i2c.setup()| 打开iic|
| i2c.send()| 向从设备写数据|
| i2c.recv()| 向从设备读取数据|
|i2c.write()| 往指定的寄存器地址 reg 传输数据|
|i2c.read()| 读取指定寄存器地址 reg 的数据内容|
> 详细的API介绍见[LuatOS-Air core API](https://doc.openluat.com/wiki/21?wiki_page_id=2254)章节
# iic使用示例
这里用一个SHT30温湿度传感器做一个演示,代码如下:
1.定义iic id号,设备地址,单次读取的命令
```
local i2c_id = 2 -- I2C id号
local i2c_addr = 0x45 -- i2c地址
local TEMP_MEASURE = {0x2C, 0x06} -- 单次读取命令
```
2.定义一个校验算法的函数
```
-- CRC8校验算法
-- data : 原始数据按字节table
-- num : 数据(table)长度
-- @return crc值
local function Calc_CRC8(data, num)
local crc, bits, bytes = 0xFF, 0, 0
for bytes = 1, num do
crc = bit.bxor(crc, data[bytes])
for bits = 8, 1, -1 do
if (bit.band(crc, 0x80) ~= 0x0) then
crc = bit.bxor(bit.clear(bit.lshift(crc, 1), 8, 9, 10), 0x31)
else
crc = bit.lshift(crc, 1)
end
end
end
return crc
end
```
3.定义一个读取传感器函数
```
-- 读取传感器
function sht30()
if i2c.setup(i2c_id, i2c.SLOW, i2c_addr) ~= i2c.SLOW then
i2c.close(i2c_id)
log.warn("SHT30", "open i2c error.")
return
end
i2c.send(i2c_id, i2c_addr, TEMP_MEASURE)
local RevData = i2c.recv(i2c_id, i2c_addr, 6)
i2c.close(i2c_id)
if RevData and #RevData >= 6 then
log.warn("SHT30", RevData:toHex())
-- 解包
local _, t_H, t_L, t_crc, h_H, h_L, h_crc = pack.unpack(RevData, 'b6')
-- 数据转换得到温湿度
local rawT, rawR = t_H * 256 or t_L, h_H * 256 or h_L -- 左移为*256
local temp, humi = -45 + rawT * 175 / 65535,
math.ceil(100 * rawR / 65535)
-- 数据检验(通过返回正确值,否则nil)
local T_Tbl, R_Tbl = {t_H, t_L}, {h_H, h_L}
local T_crc, R_crc = Calc_CRC8(T_Tbl, 2), Calc_CRC8(R_Tbl, 2)
if T_crc ~= t_crc then temp = nil end
if R_crc ~= h_crc then humi = nil end
if temp and humi then
-- body
-- 四舍五入处理
temp = string.format("%.01f", temp)
humi = string.format("%d", humi)
-- local tempBin = pack.pack(">H", temp * 10)
-- local humiBin = pack.pack("b", humi)
-- 返回
log.warn("SHT30", "temp =", temp, " humi =", humi)
return temp, humi
end
else
log.warn("SHT30", "read sensor data fail..")
end
end
```
4.启动一个循环定时器,间隔2s读取一次传感器数据
```
sys.timerLoopStart(sht30, 2000)
```
5.下载完成后重启开发板,在luatools上可以看到打印的数据:

# 硬件设计
见硬件设计指南 [I2C接口 章节](https://hmi.wiki.luatos.com/doc/65042949/e6zPC3k9/SFwDZNu0)