following this tutorial:
http://www.esp8266-projects.com/2015/04 ... -time.html
I created a file ds3231.lua with the following content:
function decToBcd(val)
local d = string.format("%d",tonumber(val / 10))
local d1 = tonumber(d*10)
local d2 = val - d1
return tonumber(d*16+d2)
end
function bcdToDec(val)
local hl=bit.rshift(val, 4)
local hh=bit.band(val,0xf)
local hr = string.format("%d%d", hl, hh)
return string.format("%d%d", hl, hh)
end
address = 0x51 -- A2, A1, A0 = 0
id=0
init = function (self, sda, scl)
self.id = 0
i2c.setup(self.id, sda, scl, i2c.SLOW)
end
readTime = function (self)
wkd = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }
i2c.start(self.id)
i2c.address(self.id, self.address, i2c.TRANSMITTER)
i2c.write(self.id, 0x00)
i2c.stop(self.id)
i2c.start(self.id)
i2c.address(self.id, self.address, i2c.RECEIVER)
c=i2c.read(self.id, 7)
i2c.stop(self.id)
return bcdToDec(string.byte(c,1)),
bcdToDec(string.byte(c,2)),
bcdToDec(string.byte(c,3)),
wkd[tonumber(bcdToDec(string.byte(c,4)))],
bcdToDec(string.byte(c,5)),
bcdToDec(string.byte(c,6)),
bcdToDec(string.byte(c,7))
end
setTime = function (self, second, minute, hour, day, date, month, year)
i2c.start(self.id)
i2c.address(self.id, self.address, i2c.TRANSMITTER)
i2c.write(self.id, 0x00)
i2c.write(self.id, decToBcd(second))
i2c.write(self.id, decToBcd(minute))
i2c.write(self.id, decToBcd(hour))
i2c.write(self.id, decToBcd(day))
i2c.write(self.id, decToBcd(date))
i2c.write(self.id, decToBcd(month))
i2c.write(self.id, decToBcd(year))
i2c.stop(self.id)
end
When I try to use this new "module" from another file (i2c_ds3231.lua) with the example code:
require('ds3231')
sda, scl = 2, 1
ds3231:init(sda, scl)
s, m, h, d, dt, mn, y = ds3231:readTime()
I get the following error:
i2c_ds3231.lua:3: attempt to index global 'ds3231' (a nil value)
Can you tell me what I did wrong?
Thank you very much!