forked from annejan/nodemcu-lua-watch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathds3231.lua
75 lines (66 loc) · 1.82 KB
/
ds3231.lua
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
--------------------------------------------------------------------------------
-- DS3231 I2C module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Tobie Booth <tbooth@hindbra.in>
--------------------------------------------------------------------------------
local moduleName = ...
local M = {}
_G[moduleName] = M
-- Default value for i2c communication
local id = 0
--device address
local dev_addr = 0x68
local function decToBcd(val)
return((val/10*16) + (val%10))
end
local function bcdToDec(val)
return((val/16*10) + (val%16))
end
-- initialize i2c
--parameters:
--d: sda
--l: scl
function M.init(d, l)
if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then
sda = d
scl = l
else
print("iic config failed!") return nil
end
print("init done")
i2c.setup(id, sda, scl, i2c.SLOW)
end
--get time from DS3231
function M.getTime()
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local c=i2c.read(id, 7)
i2c.stop(id)
return bcdToDec(tonumber(string.byte(c, 1))),
bcdToDec(tonumber(string.byte(c, 2))),
bcdToDec(tonumber(string.byte(c, 3))),
bcdToDec(tonumber(string.byte(c, 4))),
bcdToDec(tonumber(string.byte(c, 5))),
bcdToDec(tonumber(string.byte(c, 6))),
bcdToDec(tonumber(string.byte(c, 7)))
end
--set time for DS3231
function M.setTime(second, minute, hour, day, date, month, year)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.write(id, decToBcd(second))
i2c.write(id, decToBcd(minute))
i2c.write(id, decToBcd(hour))
i2c.write(id, decToBcd(day))
i2c.write(id, decToBcd(date))
i2c.write(id, decToBcd(month))
i2c.write(id, decToBcd(year))
i2c.stop(id)
end
return M