--- 模块功能:BM8563时钟功能测试
-- @author zwp0273
-- @module BM8563
-- @license MIT
-- @copyright zwp0273
-- @release 2020.12.14
require "pins"
require "ntp"
module(...,package.seeall)
local i2cslaveaddr = 0x51
local i2cid = 1
local setdata = {0x00,0x00,0x00,0x01,0x01,0x01,0x014,0x01,0x12,0x20} --地址位 秒分时 日 星期 月 年 20年 12月 14日 1时 1分 1秒 星期1 00 14/12/20
function set_BM8563(tm)
if i2c.setup(i2cid, i2c.SLOW,i2cslaveaddr) ~= i2c.SLOW then
log.info("BM8563 设置失败")
else
--tm.year % 100, tm.month, tm.day, tm.hour, tm.min, tm.sec
setdata[4] = bit.lshift(tm.sec / 10,4) + tm.sec % 10
setdata[5] = bit.lshift(tm.min / 10,4) + tm.min % 10
setdata[6] = bit.lshift(tm.hour / 10,4) + tm.hour % 10
setdata[7] = bit.lshift(tm.day / 10,4) + tm.day % 10
setdata[9] = bit.lshift(tm.month / 10,4) + tm.month % 10
setdata[10] = bit.lshift(tm.year % 100 / 10,4) + tm.year % 100 % 10
i2c.send(i2cid,i2cslaveaddr,setdata)
log.info("BM8563 设置成功")
end
i2c.close(i2cid)
end
local function read_BM8563()
---set_time()
if i2c.setup(i2cid, i2c.SLOW,i2cslaveaddr) ~= i2c.SLOW then
log.info("BM8563 打开失败")
else
i2c.send(i2cid,i2cslaveaddr,{0x02})
local data = i2c.recv(i2cid, i2cslaveaddr, 7)
local _,D1,D2,D3,D4,D5,D6,D7 = pack.unpack(data, 'b7')
D1 = 10 * bit.rshift(D1,4) + bit.band(D1,0x0f) -- 秒
D2 = 10 * bit.rshift(D2,4) + bit.band(D2,0x0f) -- 分
D3 = 10 * bit.rshift(D3,4) + bit.band(D3,0x0f) -- 小时
D4 = 10 * bit.rshift(D4,4) + bit.band(D4,0x0f) -- 日
D5 = bit.band(D5,0x0f) -- 星期
D6 = 10 * bit.rshift(D6,4) + bit.band(D6,0x0f) -- 月
D7 = 10 * bit.rshift(D7,4) + bit.band(D7,0x0f) -- 年
log.info("BM8563 read",D7,D6,D4,D3,D2,D1)
end
i2c.close(i2cid)
end
local function BM8563_to_local()
---set_time()
if i2c.setup(i2cid, i2c.SLOW,i2cslaveaddr) ~= i2c.SLOW then
log.info("BM8563 打开失败")
else
i2c.send(i2cid,i2cslaveaddr,{0x02})
local data = i2c.recv(i2cid, i2cslaveaddr, 7)
local _,D1,D2,D3,D4,D5,D6,D7 = pack.unpack(data, 'b7')
D1 = 10 * bit.rshift(D1,4) + bit.band(D1,0x0f) -- 秒
D2 = 10 * bit.rshift(D2,4) + bit.band(D2,0x0f) -- 分
D3 = 10 * bit.rshift(D3,4) + bit.band(D3,0x0f) -- 小时
D4 = 10 * bit.rshift(D4,4) + bit.band(D4,0x0f) -- 日
D5 = bit.band(D5,0x0f) -- 星期
D6 = 10 * bit.rshift(D6,4) + bit.band(D6,0x0f) -- 月
D7 = 10 * bit.rshift(D7,4) + bit.band(D7,0x0f) -- 年
misc.setClock({year=2000 + D7,month=D6,day=D4,hour=D3,min=D2,sec=D1})
log.info("BM8563 local",D7,D6,D4,D3,D2,D1)
end
i2c.close(i2cid)
end
local function time()
local rc = false
BM8563_to_local()
while true do
if ntp.isEnd() == true and rc == false then
local tm = misc.getClock()
set_BM8563(tm)
rc = true
end
if rc then read_BM8563() end
sys.wait(1000)
end
end
sys.taskInit(time)