Commit 4911d2db authored by Arnim Läuger's avatar Arnim Läuger
Browse files

Merge pull request #1336 from nodemcu/dev

1.5.1 master drop
parents c8037568 2e109686
wifi.setmode(wifi.SOFTAP); wifi.setmode(wifi.SOFTAP)
wifi.ap.config({ssid="test",pwd="12345678"}); wifi.ap.config({ssid="test",pwd="12345678"})
gpio.mode(1, gpio.OUTPUT) gpio.mode(1, gpio.OUTPUT)
srv=net.createServer(net.TCP) srv=net.createServer(net.TCP)
srv:listen(80,function(conn) srv:listen(80,function(conn)
conn:on("receive", function(client,request) conn:on("receive", function(client,request)
local buf = ""; local buf = ""
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP"); local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
if(method == nil)then if(method == nil)then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP"); _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP")
end end
local _GET = {} local _GET = {}
if (vars ~= nil)then if (vars ~= nil)then
...@@ -15,18 +15,17 @@ srv:listen(80,function(conn) ...@@ -15,18 +15,17 @@ srv:listen(80,function(conn)
_GET[k] = v _GET[k] = v
end end
end end
buf = buf.."<h1> Hello, NodeMcu.</h1><form src=\"/\">Turn PIN1 <select name=\"pin\" onchange=\"form.submit()\">"; buf = buf.."<h1> Hello, NodeMcu.</h1><form src=\"/\">Turn PIN1 <select name=\"pin\" onchange=\"form.submit()\">"
local _on,_off = "","" local _on,_off = "",""
if(_GET.pin == "ON")then if(_GET.pin == "ON")then
_on = " selected=true"; _on = " selected=true"
gpio.write(1, gpio.HIGH); gpio.write(1, gpio.HIGH)
elseif(_GET.pin == "OFF")then elseif(_GET.pin == "OFF")then
_off = " selected=\"true\""; _off = " selected=\"true\""
gpio.write(1, gpio.LOW); gpio.write(1, gpio.LOW)
end end
buf = buf.."<option".._on..">ON</opton><option".._off..">OFF</option></select></form>"; buf = buf.."<option".._on..">ON</opton><option".._off..">OFF</option></select></form>"
client:send(buf); client:send(buf)
client:close();
collectgarbage();
end) end)
conn:on("sent", function (c) c:close() end)
end) end)
------------------------------------------------------------------------------
-- BMP085 query module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
-- Heavily based on work of Christee <Christee@nodemcu.com>
--
-- Example:
-- dofile("bmp085.lua").read(sda, scl)
------------------------------------------------------------------------------
local M
do
-- cache
local i2c, tmr = i2c, tmr
-- helpers
local r8 = function(reg)
i2c.start(0)
i2c.address(0, 0x77, i2c.TRANSMITTER)
i2c.write(0, reg)
i2c.stop(0)
i2c.start(0)
i2c.address(0, 0x77, i2c.RECEIVER)
local r = i2c.read(0, 1)
i2c.stop(0)
return r:byte(1)
end
local w8 = function(reg, val)
i2c.start(0)
i2c.address(0, 0x77, i2c.TRANSMITTER)
i2c.write(0, reg)
i2c.write(0, val)
i2c.stop(0)
end
local r16u = function(reg)
return r8(reg) * 256 + r8(reg + 1)
end
local r16 = function(reg)
local r = r16u(reg)
if r > 32767 then r = r - 65536 end
return r
end
-- calibration data
local AC1, AC2, AC3, AC4, AC5, AC6, B1, B2, MB, MC, MD
-- read
local read = function(sda, scl, oss)
i2c.setup(0, sda, scl, i2c.SLOW)
-- cache calibration data
if not AC1 then
AC1 = r16(0xAA)
AC2 = r16(0xAC)
AC3 = r16(0xAE)
AC4 = r16u(0xB0)
AC5 = r16u(0xB2)
AC6 = r16u(0xB4)
B1 = r16(0xB6)
B2 = r16(0xB8)
MB = r16(0xBA)
MC = r16(0xBC)
MD = r16(0xBE)
end
-- get raw P
if not oss then oss = 0 end
if oss <= 0 then oss = 0 end
if oss > 3 then oss = 3 end
w8(0xF4, 0x34 + 64 * oss)
tmr.delay((4 + 3 ^ oss) * 1000)
local p = r8(0xF6) * 65536 + r8(0xF7) * 256 + r8(0xF8)
p = p / 2 ^ (8 - oss)
-- get T
w8(0xF4, 0x2E)
tmr.delay(5000)
local t = r16(0xF6)
local X1 = (t - AC6) * AC5 / 32768
local X2 = MC * 2048 / (X1 + MD)
t = (X2 + X1 + 8) / 16
-- normalize P
local B5 = t * 16 - 8;
local B6 = B5 - 4000
local X1 = B2 * (B6 * B6 / 4096) / 2048
local X2 = AC2 * B6 / 2048
local X3 = X1 + X2
local B3 = ((AC1 * 4 + X3) * 2 ^ oss + 2) / 4
X1 = AC3 * B6 / 8192
X2 = (B1 * (B6 * B6 / 4096)) / 65536
X3 = (X1 + X2 + 2) / 4
local B4 = AC4 * (X3 + 32768) / 32768
local B7 = (p - B3) * (50000 / 2 ^ oss)
p = B7 / B4 * 2
X1 = (p / 256) ^ 2
X1 = (X1 * 3038) / 65536
X2 = (-7357 * p) / 65536
p = p + (X1 + X2 + 3791) / 16
-- Celsius * 10, Hg mm * 10
return t, p * 3 / 40
end
-- expose
M = {
read = read,
}
end
return M
------------------------------------------------------------------------------
-- DHT11/22 query module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
--
-- Example:
-- print("DHT11", dofile("dht22.lua").read(4))
-- print("DHT22", dofile("dht22.lua").read(4, true))
-- NB: the very first read sometimes fails
------------------------------------------------------------------------------
local M
do
-- cache
local gpio = gpio
local val = gpio.read
local waitus = tmr.delay
--
local read = function(pin, dht22)
-- wait for pin value
local w = function(v)
local c = 255
while c > 0 and val(pin) ~= v do c = c - 1 end
return c
end
-- NB: we preallocate incoming data buffer
-- or precise timing in reader gets broken
local b = { 0, 0, 0, 0, 0 }
-- kick the device
gpio.mode(pin, gpio.INPUT, gpio.PULLUP)
gpio.write(pin, 1)
waitus(10)
gpio.mode(pin, gpio.OUTPUT)
gpio.write(pin, 0)
waitus(20000)
gpio.write(pin, 1)
gpio.mode(pin, gpio.INPUT, gpio.PULLUP)
-- wait for device presense
if w(0) == 0 or w(1) == 0 or w(0) == 0 then
return nil, 0
end
-- receive 5 octets of data, msb first
for i = 1, 5 do
local x = 0
for j = 1, 8 do
x = x + x
if w(1) == 0 then return nil, 1 end
-- 70us for 1, 27 us for 0
waitus(30)
if val(pin) == 1 then
x = x + 1
if w(0) == 0 then return nil, 2 end
end
end
b[i] = x
end
-- check crc. NB: calculating in receiver loop breaks timings
local crc = 0
for i = 1, 4 do
crc = (crc + b[i]) % 256
end
if crc ~= b[5] then return nil, 3 end
-- convert
local t, h
-- DHT22: values in tenths of unit, temperature can be negative
if dht22 then
h = b[1] * 256 + b[2]
t = b[3] * 256 + b[4]
if t > 0x8000 then t = -(t - 0x8000) end
-- DHT11: no negative temperatures, only integers
-- NB: return in 0.1 Celsius
else
h = 10 * b[1]
t = 10 * b[3]
end
return t, h
end
-- expose interface
M = {
read = read,
}
end
return M
-- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de>
-- licensed under the terms of the LGPL2
local moduleName = ...
local M = {}
_G[moduleName] = M
-- character table string
local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
-- encoding
function M.enc(data)
return ((data:gsub('.', function(x)
local r,b='',x:byte()
for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
return r;
end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
if (#x < 6) then return '' end
local c=0
for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
return b:sub(c+1,c+1)
end)..({ '', '==', '=' })[#data%3+1])
end
-- decoding
function M.dec(data)
data = string.gsub(data, '[^'..b..'=]', '')
return (data:gsub('.', function(x)
if (x == '=') then return '' end
local r,f='',(b:find(x)-1)
for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
return r;
end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
if (#x ~= 8) then return '' end
local c=0
for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(7-i) or 0) end
return string.char(c)
end))
end
return M
--this version actually works
local tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
base64 = {
enc = function(data)
local l,out = 0,''
local m = (3-data:len()%3)%3
local d = data..string.rep('\0',m)
for i=1,d:len() do
l = bit.lshift(l,8)
l = l+d:byte(i,i)
if i%3==0 then
for j=1,4 do
local a = bit.rshift(l,18)+1
out = out..tab:sub(a,a)
l = bit.band(bit.lshift(l,6),0xFFFFFF)
end
end
end
return out:sub(1,-1-m)..string.rep('=',m)
end,
dec = function(data)
local a,b = data:gsub('=','A')
local out = ''
local l = 0
for i=1,a:len() do
l=l+tab:find(a:sub(i,i))-1
if i%4==0 then
out=out..string.char(bit.rshift(l,16),bit.band(bit.rshift(l,8),255),bit.band(l,255))
l=0
end
l=bit.lshift(l,6)
end
return out:sub(1,-b-1)
end
}
Support for this Lua module has been discontinued.
Equivalent functionality is available from the bmp085 module in the NodeMCU
firmware code base. Refer to `docs/en/modules/bmp085.md` for API
documentation.
The original Lua code can be found in the [git repository](https://github.com/nodemcu/nodemcu-firmware/tree/2fbd5ed509964a16057b22e00aa8469d6a522d73/lua_modules/bmp085).
# BMP085 module
##Require
```lua
bmp085 = require("bmp085")
```
## Release
```lua
bmp085 = nil
package.loaded["bmp085"]=nil
```
<a id="bmp085_init"></a>
##init()
####Description
Setting the i2c pin of bmp085.<br />
####Syntax
init(sda, scl)
####Parameters
sda: 1~12, IO index.<br />
scl: 1~12, IO index.<br />
####Returns
nil
####Example
```lua
bmp085 = require("bmp085")
gpio5 = 1
gpio4 = 2
sda = gpio5
scl = gpio4
bmp085.init(sda, scl)
-- Don't forget to release it after use
bmp085 = nil
package.loaded["bmp085"]=nil
```
####See also
**-** []()
<a id="bmp085_getUP"></a>
##getUP()
####Description
Get calibrated data of pressure from bmp085.<br />
####Syntax
getUP(oss)
####Parameters
oss: Over sampling setting, which is 0,1,2,3. Default value is 0.<br />
####Returns
p: Integer, calibrated data of pressure from bmp085.
####Example
```lua
bmp085 = require("bmp085")
sda = 1
scl = 2
bmp085.init(sda, scl)
p = bmp085.getUP(oss)
print(p)
-- Don't forget to release it after use
bmp085 = nil
package.loaded["bmp085"]=nil
```
####See also
**-** []()
<a id="bmp085_getUP_raw"></a>
##getUP_raw()
####Description
Get raw data of pressure from bmp085.<br />
####Syntax
getUP_raw(oss)
####Parameters
oss: Over sampling setting, which is 0,1,2,3. Default value is 0.<br />
####Returns
up_raw: Integer, raw data of pressure from bmp085.
####Example
```lua
bmp085 = require("bmp085")
sda = 1
scl = 2
bmp085.init(sda, scl)
up = bmp085.getUP_raw(oss)
print(up)
-- Don't forget to release it after use
bmp085 = nil
package.loaded["bmp085"]=nil
```
####See also
**-** []()
<a id="bmp085_getUT"></a>
##getUT()
####Description
Get temperature from bmp085.<br />
####Syntax
getUT(num_10x)
####Parameters
num_10x: num_10x: bool value, if true, return number of 0.1 centi-degree. Default value is false, which return a string , eg: 16.7.<br />
####Returns
t: Integer or String, if num_10x is true, return number of 0.1 centi-degree, otherwise return a string.The temperature from bmp085.<br />
####Example
```lua
bmp085 = require("bmp085")
sda = 1
scl = 2
bmp085.init(sda, scl)
-- Get string of temperature.
p = bmp085.getUT(false)
print(p)
-- Get number of temperature.
p = bmp085.getUT(true)
print(p)
-- Don't forget to release it after use
bmp085 = nil
package.loaded["bmp085"]=nil
```
####See also
**-** []()
<a id="bmp085_getAL"></a>
##getAL()
####Description
Get estimated data of altitude from bmp085.<br />
####Syntax
getAL(oss)
####Parameters
oss: over sampling setting, which is 0,1,2,3. Default value is 0.<br />
####Returns
e: Integer, estimated data of altitude. Altitudi can be calculated by pressure refer to sea level pressure, which is 101325. Pressure changes 100pa corresponds to 8.43m at sea level<br />
####Example
```lua
bmp085 = require("bmp085")
sda = 1
scl = 2
bmp085.init(sda, scl)
-- Get string of temperature.
e = bmp085.getAL()
print(p)
-- Don't forget to release it after use
bmp085 = nil
package.loaded["bmp085"]=nil
```
####See also
**-** []()
--------------------------------------------------------------------------------
-- BMP085 I2C module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Christee <Christee@nodemcu.com>
--------------------------------------------------------------------------------
local moduleName = ...
local M = {}
_G[moduleName] = M
--default value for i2c communication
local id=0
--default oversampling setting
local oss = 0
--CO: calibration coefficients table.
local CO = {}
-- read reg for 1 byte
local function read_reg(dev_addr, reg_addr)
i2c.start(id)
i2c.address(id, dev_addr ,i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr,i2c.RECEIVER)
local c=i2c.read(id,1)
i2c.stop(id)
return c
end
--write reg for 1 byte
local function write_reg(dev_addr, reg_addr, reg_val)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.write(id, reg_val)
i2c.stop(id)
end
--get signed or unsigned 16
--parameters:
--reg_addr: start address of short
--signed: if true, return signed16
local function getShort(reg_addr, signed)
local tH = string.byte(read_reg(0x77, reg_addr))
local tL = string.byte(read_reg(0x77, (reg_addr + 1)))
local temp = tH*256 + tL
if (temp > 32767) and (signed == true) then
temp = temp - 65536
end
return temp
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)
--get calibration coefficients.
CO.AC1 = getShort(0xAA, true)
CO.AC2 = getShort(0xAC, true)
CO.AC3 = getShort(0xAE, true)
CO.AC4 = getShort(0xB0)
CO.AC5 = getShort(0xB2)
CO.AC6 = getShort(0xB4)
CO.B1 = getShort(0xB6, true)
CO.B2 = getShort(0xB8, true)
CO.MB = getShort(0xBA, true)
CO.MC = getShort(0xBC, true)
CO.MD = getShort(0xBE, true)
end
--get temperature from bmp085
--parameters:
--num_10x: bool value, if true, return number of 0.1 centi-degree
-- default value is false, which return a string , eg: 16.7
function M.getUT(num_10x)
write_reg(0x77, 0xF4, 0x2E);
tmr.delay(10000);
local temp = getShort(0xF6)
local X1 = (temp - CO.AC6) * CO.AC5 / 32768
local X2 = CO.MC * 2048/(X1 + CO.MD)
local r = (X2 + X1 + 8)/16
if(num_10x == true) then
return r
else
return ((r/10).."."..(r%10))
end
end
--get raw data of pressure from bmp085
--parameters:
--oss: over sampling setting, which is 0,1,2,3. Default value is 0
function M.getUP_raw(oss)
local os = 0
if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then
os = oss
end
local ov = os * 64
write_reg(0x77, 0xF4, (0x34 + ov));
tmr.delay(30000);
--delay 30ms, according to bmp085 document, wait time are:
-- 4.5ms 7.5ms 13.5ms 25.5ms respectively according to oss 0,1,2,3
local MSB = string.byte(read_reg(0x77, 0xF6))
local LSB = string.byte(read_reg(0x77, 0xF7))
local XLSB = string.byte(read_reg(0x77, 0xF8))
local up_raw = (MSB*65536 + LSB *256 + XLSB)/2^(8 - os)
return up_raw
end
--get calibrated data of pressure from bmp085
--parameters:
--oss: over sampling setting, which is 0,1,2,3. Default value is 0
function M.getUP(oss)
local os = 0
if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then
os = oss
end
local raw = M.getUP_raw(os)
local B5 = M.getUT(true) * 16 - 8;
local B6 = B5 - 4000
local X1 = CO.B2 * (B6 * B6 /4096)/2048
local X2 = CO.AC2 * B6 / 2048
local X3 = X1 + X2
local B3 = ((CO.AC1*4 + X3)*2^os + 2)/4
X1 = CO.AC3 * B6 /8192
X2 = (CO.B1 * (B6 * B6 / 4096))/65536
X3 = (X1 + X2 + 2)/4
local B4 = CO.AC4 * (X3 + 32768) / 32768
local B7 = (raw -B3) * (50000/2^os)
local p = B7/B4 * 2
X1 = (p/256)^2
X1 = (X1 *3038)/65536
X2 = (-7357 *p)/65536
p = p +(X1 + X2 + 3791)/16
return p
end
--get estimated data of altitude from bmp085
--parameters:
--oss: over sampling setting, which is 0,1,2,3. Default value is 0
function M.getAL(oss)
--Altitudi can be calculated by pressure refer to sea level pressure, which is 101325
--pressure changes 100pa corresponds to 8.43m at sea level
return (M.getUP(oss) - 101325)*843/10000
end
return M
\ No newline at end of file
# DHTxx module Support for this Lua module has been discontinued.
This module is compatible with DHT11, DHT21 and DHT22. Equivalent functionality is available from the dht module in the NodeMCU
And is able to auto-select wheather you are using DHT11 or DHT2x firmware code base. Refer to `docs/en/modules/dht.md` for API
documentation.
No need to use a resistor to connect the pin data of DHT22 to ESP8266. The original Lua code can be found in the [git repository](https://github.com/nodemcu/nodemcu-firmware/tree/2fbd5ed509964a16057b22e00aa8469d6a522d73/lua_modules/dht_lib).
##Integer Verison[When using DHT11, Float version is useless...]
### Example
```lua
PIN = 4 -- data pin, GPIO2
DHT= require("dht_lib")
DHT.read(PIN)
t = DHT.getTemperature()
h = DHT.getHumidity()
if h == nil then
print("Error reading from DHTxx")
else
-- temperature in degrees Celsius and Farenheit
print("Temperature: "..((t-(t % 10)) / 10).."."..(t % 10).." deg C")
print("Temperature: "..(9 * t / 50 + 32).."."..(9 * t / 5 % 10).." deg F")
-- humidity
print("Humidity: "..((h - (h % 10)) / 10).."."..(h % 10).."%")
end
-- release module
DHT = nil
package.loaded["dht_lib"]=nil
```
##Float Verison
###Example
```lua
PIN = 4 -- data pin, GPIO2
DHT= require("dht_lib")
DHT.read(PIN)
t = DHT.getTemperature()
h = DHT.getHumidity()
if h == nil then
print("Error reading from DHT11/22")
else
-- temperature in degrees Celsius and Farenheit
-- floating point and integer version:
print("Temperature: "..(t/10).." deg C")
print("Temperature: "..(9 * t / 50 + 32).." deg F")
-- humidity
print("Humidity: "..(h/10).."%")
end
-- release module
DHT = nil
package.loaded["dht_lib"]=nil
```
## Functions
###read
read(pin)
Read humidity and temperature from DHTxx(11,21,22...).
**Parameters:**
* pin - ESP8266 pin connect to data pin
### getHumidity
getHumidity()
Returns the humidity of the last reading.
**Returns:**
* last humidity reading in per thousand
### getTemperature
getTemperature()
Returns the temperature of the last reading.
**Returns:**
* last temperature reading in(dht22) 0.1ºC (dht11)1ºC
*
-- ***************************************************************************
-- DHTxx(11,21,22) module for ESP8266 with nodeMCU
--
-- Written by Javier Yanez mod by Martin
-- but based on a script of Pigs Fly from ESP8266.com forum
--
-- MIT license, http://opensource.org/licenses/MIT
-- ***************************************************************************
--Support list:
--DHT11 Tested
--DHT21 Not Test yet
--DHT22(AM2302) Tested
--AM2320 Not Test yet
--Output format-> Real temperature times 10(or DHT22 will miss it float part in Int Version)
--==========================Module Part======================
local moduleName = ...
local M = {}
_G[moduleName] = M
--==========================Local the UMI and TEMP===========
local humidity
local temperature
--==========================Local the bitStream==============
local bitStream = {}
---------------------------Read bitStream from DHTXX--------------------------
local function read(pin)
local bitlength = 0
humidity = 0
temperature = 0
-- Use Markus Gritsch trick to speed up read/write on GPIO
local gpio_read = gpio.read
for j = 1, 40, 1 do
bitStream[j] = 0
end
-- Step 1: send out start signal to DHT22
gpio.mode(pin, gpio.OUTPUT)
gpio.write(pin, gpio.HIGH)
tmr.delay(100)
gpio.write(pin, gpio.LOW)
tmr.delay(20000)
gpio.write(pin, gpio.HIGH)
gpio.mode(pin, gpio.INPUT)
-- Step 2: Receive bitStream from DHT11/22
-- bus will always let up eventually, don't bother with timeout
while (gpio_read(pin) == 0 ) do end
local c=0
while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end
-- bus will always let up eventually, don't bother with timeout
while (gpio_read(pin) == 0 ) do end
c=0
while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end
-- Step 3: DHT22 send data
for j = 1, 40, 1 do
while (gpio_read(pin) == 1 and bitlength < 10 ) do
bitlength = bitlength + 1
end
bitStream[j] = bitlength
bitlength = 0
-- bus will always let up eventually, don't bother with timeout
while (gpio_read(pin) == 0) do end
end
end
---------------------------Check out the data--------------------------
----Auto Select the DHT11/DHT22 By check the byte[1] && byte[3] -------
---------------Which is empty when using DHT11-------------------------
function M.read(pin)
read(pin)
local byte_0 = 0
local byte_1 = 0
local byte_2 = 0
local byte_3 = 0
local byte_4 = 0
for i = 1, 8, 1 do -- Byte[0]
if (bitStream[i] > 3) then
byte_0 = byte_0 + 2 ^ (8 - i)
end
end
for i = 1, 8, 1 do -- Byte[1]
if (bitStream[i+8] > 3) then
byte_1 = byte_1 + 2 ^ (8 - i)
end
end
for i = 1, 8, 1 do -- Byte[2]
if (bitStream[i+16] > 3) then
byte_2 = byte_2 + 2 ^ (8 - i)
end
end
for i = 1, 8, 1 do -- Byte[3]
if (bitStream[i+24] > 3) then
byte_2 = byte_2 + 2 ^ (8 - i)
end
end
for i = 1, 8, 1 do -- Byte[4]
if (bitStream[i+32] > 3) then
byte_4 = byte_4 + 2 ^ (8 - i)
end
end
if byte_1==0 and byte_3 == 0 then
---------------------------Convert the bitStream into Number through DHT11's Way--------------------------
--As for DHT11 40Bit is consisit of 5Bytes
--First byte->Humidity Data's Int part
--Sencond byte->Humidity Data's Float Part(Which should be empty)
--Third byte->Temp Data;s Intpart
--Forth byte->Temp Data's Float Part(Which should be empty)
--Fifth byte->SUM Byte, Humi+Temp
if(byte_4 ~= byte_0+byte_2) then
humidity = nil
temperature = nil
else
humidity = byte_0 *10 -- In order to universe with the DHT22
temperature = byte_2 *10
end
else ---------------------------Convert the bitStream into Number through DHT22's Way--------------------------
--As for DHT22 40Bit is consisit of 5Bytes
--First byte->Humidity Data's High Bit
--Sencond byte->Humidity Data's Low Bit(And if over 0x8000, use complement)
--Third byte->Temp Data's High Bit
--Forth byte->Temp Data's Low Bit
--Fifth byte->SUM Byte
humidity = byte_0 * 256 + byte_1
temperature = byte_2 * 256 + byte_3
checksum = byte_4
checksumTest = (bit.band(humidity, 0xFF) + bit.rshift(humidity, 8) + bit.band(temperature, 0xFF) + bit.rshift(temperature, 8))
checksumTest = bit.band(checksumTest, 0xFF)
if temperature > 0x8000 then
-- convert to negative format
temperature = -(temperature - 0x8000)
end
-- conditions compatible con float point and integer
if (checksumTest - checksum >= 1) or (checksum - checksumTest >= 1) then
humidity = nil
end
end
byte_0 = nil
byte_1 = nil
byte_2 = nil
byte_3 = nil
byte_4 = nil
end
--------------API for geting the data out------------------
function M.getTemperature()
return temperature
end
function M.getHumidity()
return humidity
end
-------------Return Index------------------------------------
return M
...@@ -13,6 +13,14 @@ end ...@@ -13,6 +13,14 @@ end
-- Just read temperature -- Just read temperature
print("Temperature: "..t.read().."'C") print("Temperature: "..t.read().."'C")
-- Get temperature of first detected sensor in Fahrenheit
print("Temperature: "..t.read(nil,t.F).."'F")
-- Query the second detected sensor, get temperature in Kelvin
if (table.getn(addrs) >= 2) then
print("Second sensor: "..t.read(addrs[2],t.K).."'K")
end
-- Don't forget to release it after use -- Don't forget to release it after use
t = nil t = nil
ds18b20 = nil ds18b20 = nil
......
...@@ -33,9 +33,9 @@ setfenv(1,M) ...@@ -33,9 +33,9 @@ setfenv(1,M)
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
-- Implementation -- Implementation
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
C = 0 C = 'C'
F = 1 F = 'F'
K = 2 K = 'K'
function setup(dq) function setup(dq)
pin = dq pin = dq
if(pin == nil) then if(pin == nil) then
......
...@@ -40,9 +40,10 @@ package.loaded["ds3231"]=nil ...@@ -40,9 +40,10 @@ package.loaded["ds3231"]=nil
## setTime() ## setTime()
####Description ####Description
Sets the current date and time. Sets the current date and time.
if _disableOscillator_ is set to 1 the oscillator will **stop** on battery.
####Syntax ####Syntax
setTime(second, minute, hour, day, date, month, year) setTime(second, minute, hour, day, date, month, year, disableOscillator)
####Parameters ####Parameters
second: 00-59 second: 00-59
...@@ -52,6 +53,7 @@ day: 1-7 (Sunday = 1, Saturday = 7) ...@@ -52,6 +53,7 @@ day: 1-7 (Sunday = 1, Saturday = 7)
date: 01-31 date: 01-31
month: 01-12 month: 01-12
year: 00-99 year: 00-99
disableOscillator: (optional) 0-1
####Returns ####Returns
nil nil
...@@ -112,3 +114,241 @@ package.loaded["ds3231"]=nil ...@@ -112,3 +114,241 @@ package.loaded["ds3231"]=nil
``` ```
####See also ####See also
**-** []() **-** []()
<a id="ds3231_setAlarm"></a>
## setAlarm()
####Description
Set an alarm to be triggered on SQW pin:
_alarm1_ has a precision of **seconds**; _alarm2_ has a precision of **minutes** (`second` parameter will be ignored).
Alarms sets gpio.LOW over the SQW pin and let it unchanged until reloaded. When reloaded sets gpio.HIGH.
Alarms trigger **only once**, after that, if you want them to trigger again, you need to call `reloadAlarms()` or `setAlarm(...)` again.
Alarm type set the alarm match conditions:
- `ds3231.EVERYSECOND` works only with _alarm1_ and triggers every second;
- `ds3231.EVERYMINUTE` works only with _alarm2_ and triggers every minute (at 00 seconds);
- `ds3231.SECOND` triggers when time match given `seconds` parameter;
- `ds3231.MINUTE` triggers when time match given `seconds` and `minutes` parameters;
- `ds3231.HOUR` triggers when time match given `seconds`, `minutes`, and `hours` parameters;
- `ds3231.DAY` triggers when time match given `seconds`, `minutes`, and `hours` on week day `date/day` parameters;
- `ds3231.DATE` triggers when time match given `seconds`, `minutes`, and `hours` on date (day of the month) `date/day` parameters;
####Syntax
setAlarm(alarmId, alarmType, seconds, minutes, hours, date/day)
####Parameters
alarmId: 1-2
alarmType: 1-7
seconds: 00-59
minutes: 00-59
hours: 00-23
date/day: 01-31 or 1-7 (Sunday = 1, Saturday = 7)
####Returns
nil
####Example
```lua
ds3231=require("ds3231")
ds3231.init(3, 4)
-- Setting PIN1 to triggers on interrupt when alarm triggers
gpio.mode(1,gpio.INT)
gpio.trig(1,'down',function(level)
print('Time is passing')
-- If not reloaded it will be triggered only once
ds3231.reloadAlarms()
end)
ds3231.setAlarm(2,ds3231.EVERYMINUTE)
-- Don't forget to release it after use
ds3231 = nil
package.loaded["ds3231"]=nil
```
####See also
**-** []()
<a id="ds3231_reloadAlarms"></a>
## reloadAlarms()
####Description
Reload an already triggered alarm. Otherwise it will never be triggered again.
There are two different alarms and they have to be reloaded both to let, even only one, to be triggered again. So there isn't a param to select which alarm to reload.
####Syntax
reloadAlarms()
####Parameters
nil
####Returns
nil
####Example
```lua
ds3231=require("ds3231")
ds3231.init(3, 4)
-- Setting PIN1 to triggers on interrupt when alarm triggers
gpio.mode(1,gpio.INT)
gpio.trig(1,'down',function(level)
print('Time is passing')
-- If not reloaded it will be triggered only once
ds3231.reloadAlarms()
end)
ds3231.setAlarm(2,ds3231.EVERYMINUTE)
-- Don't forget to release it after use
ds3231 = nil
package.loaded["ds3231"]=nil
```
####See also
**-** []()
<a id="ds3231_enableAlarm"></a>
## enableAlarm()
####Description
Enable an already setted alarm with the previous matching conditions. It reloads alarms internally.
####Syntax
enableAlarm(alarmId)
####Parameters
alarmId: 1-2
####Returns
nil
####Example
```lua
ds3231=require("ds3231")
ds3231.init(3, 4)
-- Trigger on x:20:15
ds3231.setAlarm(1,ds3231.MINUTE,15,20)
if badThing == 1 then
ds3231.disableAlarm(1)
end
if goodThing == 1 then
ds3231.enableAlarm(1)
end
-- Don't forget to release it after use
ds3231 = nil
package.loaded["ds3231"]=nil
```
####See also
**-** []()
<a id="ds3231_disableAlarm"></a>
## disableAlarm()
####Description
Disable an already setted alarm with the previous matching conditions.
if _alarmId_ is not 1 or 2 it disables both alarms.
**Warning**: `disableAlarm()` prevent alarms to trigger interrupt over SQW pin but alarm itself will triggers at the matching conditions as it could be seen on _status byte_.
####Syntax
disableAlarm(alarmId)
####Parameters
alarmId: 0-2
####Returns
nil
####Example
```lua
ds3231=require("ds3231")
ds3231.init(3, 4)
-- Trigger on x:20:15
ds3231.setAlarm(1,ds3231.MINUTE,15,20)
if badThing == 1 then
ds3231.disableAlarm(1)
end
if goodThing == 1 then
ds3231.enableAlarm(1)
end
-- Don't forget to release it after use
ds3231 = nil
package.loaded["ds3231"]=nil
```
####See also
**-** []()
<a id="ds3231_getBytes"></a>
## getBytes()
####Description
Get bytes of control, for debug purpose, and status of DS3231. To see what they means check the [Datasheet](http://datasheets.maximintegrated.com/en/ds/DS3231.pdf)
####Syntax
getBytes()
####Parameters
nil
####Returns
control: integer. Control 0-255
status: integer. Status 0-143 (bit 6-5-4 unused)
####Example
```lua
ds3231=require("ds3231")
ds3231.init(3, 4)
control,status = ds3231.getBytes()
print('Control byte: '..control)
print('Status byte: '..status)
-- Don't forget to release it after use
ds3231 = nil
package.loaded["ds3231"]=nil
```
####See also
**-** []()
<a id="ds3231_resetStopFlag"></a>
## resetStopFlag()
####Description
Stop flag on status byte means that the oscillator either is stopped or was stopped for some period and may be used to judge the validity of the timekeeping data.
When setted to 1 this flag keeps that values until changed to 0.
Call `resetStopFlag()` if you need to check validity of time data after that.
####Syntax
resetStopFlag()
####Parameters
nil
####Returns
nil
####Example
```lua
ds3231=require("ds3231")
ds3231.init(3, 4)
control,status = ds3231.getBytes()
if bit.band(bit.rshift(status, 7),1) == 1 then
print('[WARNING] RTC has stopped')
ds3231.resetStopFlag()
end
-- Don't forget to release it after use
ds3231 = nil
package.loaded["ds3231"]=nil
```
####See also
**-** []()
\ No newline at end of file
...@@ -9,6 +9,16 @@ local moduleName = ... ...@@ -9,6 +9,16 @@ local moduleName = ...
local M = {} local M = {}
_G[moduleName] = M _G[moduleName] = M
-- Constants:
M.EVERYSECOND = 6
M.EVERYMINUTE = 7
M.SECOND = 1
M.MINUTE = 2
M.HOUR = 3
M.DAY = 4
M.DATE = 5
M.DISABLE = 0
-- Default value for i2c communication -- Default value for i2c communication
local id = 0 local id = 0
...@@ -16,6 +26,7 @@ local id = 0 ...@@ -16,6 +26,7 @@ local id = 0
local dev_addr = 0x68 local dev_addr = 0x68
local function decToBcd(val) local function decToBcd(val)
if val == nil then return 0 end
return((((val/10) - ((val/10)%1)) *16) + (val%10)) return((((val/10) - ((val/10)%1)) *16) + (val%10))
end end
...@@ -23,6 +34,11 @@ local function bcdToDec(val) ...@@ -23,6 +34,11 @@ local function bcdToDec(val)
return((((val/16) - ((val/16)%1)) *10) + (val%16)) return((((val/16) - ((val/16)%1)) *10) + (val%16))
end end
local function addAlarmBit(val,day)
if day == 1 then return bit.bor(val,64) end
return bit.bor(val,128)
end
-- initialize i2c -- initialize i2c
--parameters: --parameters:
--d: sda --d: sda
...@@ -32,9 +48,9 @@ function M.init(d, l) ...@@ -32,9 +48,9 @@ function M.init(d, l)
sda = d sda = d
scl = l scl = l
else else
print("iic config failed!") return nil print("[ERROR] i2c config failed!") return nil
end end
print("init done") print("[LOG] DS3231 init done")
i2c.setup(id, sda, scl, i2c.SLOW) i2c.setup(id, sda, scl, i2c.SLOW)
end end
...@@ -58,7 +74,8 @@ function M.getTime() ...@@ -58,7 +74,8 @@ function M.getTime()
end end
--set time for DS3231 --set time for DS3231
function M.setTime(second, minute, hour, day, date, month, year) -- enosc setted to 1 disables oscilation on battery, stopping time
function M.setTime(second, minute, hour, day, date, month, year, disOsc)
i2c.start(id) i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER) i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x00) i2c.write(id, 0x00)
...@@ -70,6 +87,179 @@ function M.setTime(second, minute, hour, day, date, month, year) ...@@ -70,6 +87,179 @@ function M.setTime(second, minute, hour, day, date, month, year)
i2c.write(id, decToBcd(month)) i2c.write(id, decToBcd(month))
i2c.write(id, decToBcd(year)) i2c.write(id, decToBcd(year))
i2c.stop(id) i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0E)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local c = string.byte(i2c.read(id, 1), 1)
i2c.stop(id)
if disOsc == 1 then c = bit.bor(c,128)
else c = bit.band(c,127) end
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0E)
i2c.write(id, c)
i2c.stop(id)
end
-- Reset alarmId flag to let alarm to be triggered again
function M.reloadAlarms ()
if bit == nil or bit.band == nil or bit.bor == nil then
print("[ERROR] Module bit is required to use alarm function")
return nil
end
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0F)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local d = string.byte(i2c.read(id, 1), 1)
i2c.stop(id)
-- Both flag needs to be 0 to let alarms trigger
d = bit.band(d,252)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0F)
i2c.write(id, d)
i2c.stop(id)
print('[LOG] Alarm '..almId..' reloaded')
end
-- Enable alarmId bit. Let it to be triggered
function M.enableAlarm (almId)
if bit == nil or bit.band == nil or bit.bor == nil then
print("[ERROR] Module bit is required to use alarm function")
return nil
end
if almId ~= 1 and almId ~= 2 then print('[ERROR] Wrong alarm id (1 or 2): '..almId) return end
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0E)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local c = string.byte(i2c.read(id, 1), 1)
i2c.stop(id)
c = bit.bor(c,4)
if almId == 1 then c = bit.bor(c,1)
else c = bit.bor(c,2) end
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0E)
i2c.write(id, c)
i2c.stop(id)
M.reloadAlarms()
print('[LOG] Alarm '..almId..' enabled')
end
-- If almID equals 1 or 2 disable that alarm, otherwise disables both.
function M.disableAlarm (almId)
if bit == nil or bit.band == nil or bit.bor == nil then
print("[ERROR] Module bit is required to use alarm function")
return nil
end
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0E)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local c = string.byte(i2c.read(id, 1), 1)
i2c.stop(id)
if almId == 1 then c = bit.band(c, 254)
elseif almId == 2 then c = bit.band(c, 253)
else
almId = '1 and 2'
c = bit.band(c, 252)
end
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0E)
i2c.write(id, c)
i2c.stop(id)
print('[LOG] Alarm '..almId..' disabled')
end
-- almId can be 1 or 2;
-- almType should be taken from constants
function M.setAlarm (almId, almType, second, minute, hour, date)
if bit == nil or bit.band == nil or bit.bor == nil then
print("[ERROR] Module bit is required to use alarm function")
return nil
end
if almId ~= 1 and almId ~= 2 then print('[ERROR] Wrong alarm id (1 or 2): '..almId) return end
M.enableAlarm(almId)
second = decToBcd(second)
minute = decToBcd(minute)
hour = decToBcd(hour)
date = decToBcd(date)
if almType == M.EVERYSECOND or almType == M.EVERYMINUTE then
second = addAlarmBit(second)
minute = addAlarmBit(minute)
hour = addAlarmBit(hour)
date = addAlarmBit(date)
elseif almType == M.SECOND then
minute = addAlarmBit(minute)
hour = addAlarmBit(hour)
date = addAlarmBit(date)
elseif almType == M.MINUTE then
hour = addAlarmBit(hour)
date = addAlarmBit(date)
elseif almType == M.HOUR then
date = addAlarmBit(date)
elseif almType == M.DAY then
date = addAlarmBit(date,1)
end
local almStart = 0x07
if almId == 2 then almStart = 0x0B end
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, almStart)
if almId == 1 then i2c.write(id, second) end
i2c.write(id, minute)
i2c.write(id, hour)
i2c.write(id, date)
i2c.stop(id)
print('[LOG] Alarm '..almId..' setted')
end
-- Get Control and Status bytes
function M.getBytes ()
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0E)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local c = i2c.read(id, 2)
i2c.stop(id)
return tonumber(string.byte(c, 1)), tonumber(string.byte(c, 2))
end
-- Resetting RTC Stop Flag
function M.resetStopFlag ()
if bit == nil or bit.band == nil or bit.bor == nil then
print("[ERROR] Module bit is required to reset stop flag")
return nil
end
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0F)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr, i2c.RECEIVER)
local s = string.byte(i2c.read(id, 1))
i2c.stop(id)
s = bit.band(s,127)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, 0x0F)
i2c.write(id, s)
i2c.stop(id)
print('[LOG] RTC stop flag resetted')
end end
return M return M
# LM92 module # LM92 module
This module adds basic support for the LM92 +-0.33C 12bit+sign temperature sensor. More details in the [datasheet](http://www.ti.com/lit/ds/symlink/lm92.pdf). This module adds basic support for the LM92 +-0.33C 12bit+sign temperature sensor. More details in the [datasheet](http://www.ti.com/lit/ds/symlink/lm92.pdf).
Works: Works:
- 06/01/2016: Add get/set comparison registers. Thyst, Tlow, Thigh and Tcrit
- getting the temperature - getting the temperature
- entering the chip's to shutdown mode (350uA -> 5uA power consumption) - entering the chip's to shutdown mode (350uA -> 5uA power consumption)
- waking up the chip from shutdown - waking up the chip from shutdown
...@@ -94,5 +95,181 @@ shutdown() ...@@ -94,5 +95,181 @@ shutdown()
```lua ```lua
LM92.shutdown() LM92.shutdown()
``` ```
##setThyst()
####Description
Set hysteresis Temperature.
####Syntax
setThyst(data_wr)
####Parameters
data_wr: 130~-55 ºC, hysteresis Temperature
####Returns
nil
####Example
```lua
LM92.setThyst(3)
```
##setTcrit()
####Description
Set Critical Temperature.
####Syntax
setTcrit(data_wr)
####Parameters
data_wr: 130~-55 ºC, Critical Temperature
####Returns
nil
####Example
```lua
LM92.setTcrit(100.625)
```
##setTlow()
####Description
Set Low Window Temperature.
####Syntax
setTlow(data_wr)
####Parameters
data_wr: 130~-55 ºC, Low Window Temperature
####Returns
nil
####Example
```lua
LM92.setTlow(32.25)
```
##setThigh()
####Description
Set High Window Temperature.
####Syntax
setThigh(data_wr)
####Parameters
data_wr: 130~-55 ºC, High Window Temperature
####Returns
nil
####Example
```lua
LM92.setThigh(27.5)
```
##getThyst()
####Description
Get hysteresis Temperature.
####Syntax
getThyst()
####Parameters
--
####Returns
Hysteresis Temperature in degree Celsius.
####Example
```lua
t = LM92.getThyst()
print("Got hysteresis temperature: "..t.." C")
```
##getTcrit()
####Description
Get Critical Temperature.
####Syntax
getTcrit()
####Parameters
--
####Returns
Critical Temperature in degree Celsius.
####Example
```lua
t = LM92.getTcrit()
print("Got Critical temperature: "..t.." C")
```
##getTlow()
####Description
Get Low Window Temperature.
####Syntax
getTlow()
####Parameters
--
####Returns
Low Window Temperature in degree Celsius.
####Example
```lua
t = LM92.getTlow()
print("Got Low Window temperature: "..t.." C")
```
##getThigh()
####Description
Get High Window Temperature.
####Syntax
getThigh()
####Parameters
--
####Returns
High Window Temperature in degree Celsius.
####Example
```lua
t = LM92.getThigh()
print("Got High Window temperature: "..t.." C")
```
##Full example
--node.compile("lm92.lua")
LM92 = require("lm92")
gpio0 = 3
gpio2 = 4
sda = gpio0
scl = gpio2
addr = 0x48
LM92.init(sda, scl,addr)
t = LM92.getTemperature()
print("Got temperature: "..t.." C")
--Seting comparison temperatures
LM92.setThyst(3)
LM92.setTcrit(40.75)
LM92.setTlow(28.5)
LM92.setThigh(31.625)
t = LM92.getThyst()
print("Got hyster: "..t.." C")
t = LM92.getTcrit()
print("Got Crit: "..t.." C")
t = LM92.getTlow()
print("Got Low: "..t.." C")
t = LM92.getThigh()
print("Got High: "..t.." C")
#### TODO: #### TODO:
- add full support of the features, including interrupt and critical alert support - add full support of the features, including interrupt and critical alert support
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
-- --
-- Written by Levente Tamas <levente.tamas@navicron.com> -- Written by Levente Tamas <levente.tamas@navicron.com>
-- --
-- modify by Garberoglio Leonardo <leogarberoglio@gmail.com>
--
-- GNU LGPL, see https://www.gnu.org/copyleft/lesser.html -- GNU LGPL, see https://www.gnu.org/copyleft/lesser.html
-- ****************************************************** -- ******************************************************
...@@ -47,6 +49,15 @@ local function write_reg(reg_addr, data) ...@@ -47,6 +49,15 @@ local function write_reg(reg_addr, data)
i2c.stop(id) i2c.stop(id)
end end
--write comparison reg with 2 bytes
local function write_comp_reg(reg_addr, msb, lsb)
i2c.start(id)
i2c.address(id, address, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.write(id, msb)
i2c.write(id, lsb)
i2c.stop(id)
end
-- initialize i2c -- initialize i2c
-- d: sda -- d: sda
-- c: scl -- c: scl
...@@ -90,5 +101,96 @@ function M.wakeup() ...@@ -90,5 +101,96 @@ function M.wakeup()
write_reg(0x01,0x00) write_reg(0x01,0x00)
end end
-- Write the LM92 Thyst SET POINT
function M.setThyst(data_wr)
local tmp = data_wr / 0.0625
if (tmp>=0x1000) then
tmp= tmp-0x2000 --convert the two's complement
end
tmp = bit.lshift(tmp,3)
local lsb = bit.band(tmp, 0x00FF)
tmp = bit.rshift(bit.band(tmp, 0xFF00),8)
write_comp_reg(0x02,tmp, lsb)
end
-- Write the LM92 T_crit SET POINT
function M.setTcrit(data_wr)
local tmp = data_wr / 0.0625
if (tmp>=0x1000) then
tmp= tmp-0x2000 --convert the two's complement
end
tmp = bit.lshift(tmp,3)
local lsb = bit.band(tmp, 0x00FF)
tmp = bit.rshift(bit.band(tmp, 0xFF00),8)
write_comp_reg(0x03,tmp, lsb)
end
-- Write the LM92 Tlow SET POINT
function M.setTlow(data_wr)
local tmp = data_wr / 0.0625
if (tmp>=0x1000) then
tmp= tmp-0x2000 --convert the two's complement
end
tmp = bit.lshift(tmp,3)
local lsb = bit.band(tmp, 0x00FF)
tmp = bit.rshift(bit.band(tmp, 0xFF00),8)
write_comp_reg(0x04,tmp, lsb)
end
-- Write the LM92 T_high SET POINT
function M.setThigh(data_wr)
local tmp = data_wr / 0.0625
if (tmp>=0x1000) then
tmp= tmp-0x2000 --convert the two's complement
end
tmp = bit.lshift(tmp,3)
local lsb = bit.band(tmp, 0x00FF)
tmp = bit.rshift(bit.band(tmp, 0xFF00),8)
write_comp_reg(0x05,tmp, lsb)
end
-- Read the LM92 Thyst SET POINT
function M.getThyst()
local temperature
local tmp=read_reg(0x02,2) --read 2 bytes from the Hysteresis register
temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits
if (temperature>=0x1000) then
temperature= temperature-0x2000 --convert the two's complement
end
return temperature * 0.0625
end
-- Read the LM92 T_crit SET POINT
function M.getTcrit()
local temperature
local tmp=read_reg(0x03,2) --read 2 bytes from the T Critical register
temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits
if (temperature>=0x1000) then
temperature= temperature-0x2000 --convert the two's complement
end
return temperature * 0.0625
end
-- Read the LM92 Tlow SET POINT
function M.getTlow()
local temperature
local tmp=read_reg(0x04,2) --read 2 bytes from the T Low register
temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits
if (temperature>=0x1000) then
temperature= temperature-0x2000 --convert the two's complement
end
return temperature * 0.0625
end
-- Read the LM92 T_high SET POINT
function M.getThigh()
local temperature
local tmp=read_reg(0x05,2) --read 2 bytes from the T High register
temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits
if (temperature>=0x1000) then
temperature= temperature-0x2000 --convert the two's complement
end
return temperature * 0.0625
end
return M return M
Support for this Lua module has been discontinued.
Equivalent functionality is available from the dht module in the NodeMCU
firmware code base. Refer to `docs/en/modules/tsl2561.md` for API
documentation.
The original Lua code can be found in the [git repository](https://github.com/nodemcu/nodemcu-firmware/tree/2fbd5ed509964a16057b22e00aa8469d6a522d73/lua_modules/tsl2561).
-- ***************************************************************************
-- tsl2561.lua
-- Module for ESP8266 with nodeMCU
-- Ported from github.com/Seeed-Studio/Grove_Digital_Light_Sensor
--
-- Copyright (c) 2012 seeed technology inc.
-- Website : www.seeed.cc
-- Author : zhangkun
-- Create Time:
-- Change Log : 2015-07-21: Ported original code to Lua
-- by Marius Schmeding (skybus.io)
--
-- MIT License, http://opensource.org/licenses/MIT
-- ***************************************************************************
local TSL2561_Control = 0x80
local TSL2561_Timing = 0x81
local TSL2561_Interrupt = 0x86
local TSL2561_Channel0L = 0x8C
local TSL2561_Channel0H = 0x8D
local TSL2561_Channel1L = 0x8E
local TSL2561_Channel1H = 0x8F
local TSL2561_Address = 0x29 -- device address
local LUX_SCALE = 14 -- scale by 2^14
local RATIO_SCALE = 9 -- scale ratio by 2^9
local CH_SCALE = 10 -- scale channel values by 2^10
local CHSCALE_TINT0 = 0x7517 -- 322/11 * 2^CH_SCALE
local CHSCALE_TINT1 = 0x0fe7 -- 322/81 * 2^CH_SCALE
-- Scale table
local S = {}
S.K1T = 0x0040 -- 0.125 * 2^RATIO_SCALE
S.B1T = 0x01f2 -- 0.0304 * 2^LUX_SCALE
S.M1T = 0x01be -- 0.0272 * 2^LUX_SCALE
S.K2T = 0x0080 -- 0.250 * 2^RATIO_SCA
S.B2T = 0x0214 -- 0.0325 * 2^LUX_SCALE
S.M2T = 0x02d1 -- 0.0440 * 2^LUX_SCALE
S.K3T = 0x00c0 -- 0.375 * 2^RATIO_SCALE
S.B3T = 0x023f -- 0.0351 * 2^LUX_SCALE
S.M3T = 0x037b -- 0.0544 * 2^LUX_SCALE
S.K4T = 0x0100 -- 0.50 * 2^RATIO_SCALE
S.B4T = 0x0270 -- 0.0381 * 2^LUX_SCALE
S.M4T = 0x03fe -- 0.0624 * 2^LUX_SCALE
S.K5T = 0x0138 -- 0.61 * 2^RATIO_SCALE
S.B5T = 0x016f -- 0.0224 * 2^LUX_SCALE
S.M5T = 0x01fc -- 0.0310 * 2^LUX_SCALE
S.K6T = 0x019a -- 0.80 * 2^RATIO_SCALE
S.B6T = 0x00d2 -- 0.0128 * 2^LUX_SCALE
S.M6T = 0x00fb -- 0.0153 * 2^LUX_SCALE
S.K7T = 0x029a -- 1.3 * 2^RATIO_SCALE
S.B7T = 0x0018 -- 0.00146 * 2^LUX_SCALE
S.M7T = 0x0012 -- 0.00112 * 2^LUX_SCALE
S.K8T = 0x029a -- 1.3 * 2^RATIO_SCALE
S.B8T = 0x0000 -- 0.000 * 2^LUX_SCALE
S.M8T = 0x0000 -- 0.000 * 2^LUX_SCALE
S.K1C = 0x0043 -- 0.130 * 2^RATIO_SCALE
S.B1C = 0x0204 -- 0.0315 * 2^LUX_SCALE
S.M1C = 0x01ad -- 0.0262 * 2^LUX_SCALE
S.K2C = 0x0085 -- 0.260 * 2^RATIO_SCALE
S.B2C = 0x0228 -- 0.0337 * 2^LUX_SCALE
S.M2C = 0x02c1 -- 0.0430 * 2^LUX_SCALE
S.K3C = 0x00c8 -- 0.390 * 2^RATIO_SCALE
S.B3C = 0x0253 -- 0.0363 * 2^LUX_SCALE
S.M3C = 0x0363 -- 0.0529 * 2^LUX_SCALE
S.K4C = 0x010a -- 0.520 * 2^RATIO_SCALE
S.B4C = 0x0282 -- 0.0392 * 2^LUX_SCALE
S.M4C = 0x03df -- 0.0605 * 2^LUX_SCALE
S.K5C = 0x014d -- 0.65 * 2^RATIO_SCALE
S.B5C = 0x0177 -- 0.0229 * 2^LUX_SCALE
S.M5C = 0x01dd -- 0.0291 * 2^LUX_SCALE
S.K6C = 0x019a -- 0.80 * 2^RATIO_SCALE
S.B6C = 0x0101 -- 0.0157 * 2^LUX_SCALE
S.M6C = 0x0127 -- 0.0180 * 2^LUX_SCALE
S.K7C = 0x029a -- 1.3 * 2^RATIO_SCALE
S.B7C = 0x0037 -- 0.00338 * 2^LUX_SCALE
S.M7C = 0x002b -- 0.00260 * 2^LUX_SCALE
S.K8C = 0x029a -- 1.3 * 2^RATIO_SCALE
S.B8C = 0x0000 -- 0.000 * 2^LUX_SCALE
S.M8C = 0x0000 -- 0.000 * 2^LUX_SCALE
local moduleName = ...
local M = {}
_G[moduleName] = M
-- i2c interface ID
local id = 0
-- local vars
local ch0,ch1,chScale,channel1,channel0,ratio1,b,m,temp,lux = 0
-- Wrapping I2C functions to retain original calls
local Wire = {}
function Wire.beginTransmission(ADDR)
i2c.start(id)
i2c.address(id, ADDR, i2c.TRANSMITTER)
end
function Wire.write(commands)
i2c.write(id, commands)
end
function Wire.endTransmission()
i2c.stop(id)
end
function Wire.requestFrom(ADDR, length)
i2c.start(id)
i2c.address(id, ADDR,i2c.RECEIVER)
c = i2c.read(id, length)
i2c.stop(id)
return string.byte(c)
end
local function readRegister(deviceAddress, address)
Wire.beginTransmission(deviceAddress)
Wire.write(address) -- register to read
Wire.endTransmission()
value = Wire.requestFrom(deviceAddress, 1) -- read a byte
return value
end
local function writeRegister(deviceAddress, address, val)
Wire.beginTransmission(deviceAddress) -- start transmission to device
Wire.write(address) -- send register address
Wire.write(val) -- send value to write
Wire.endTransmission() -- end transmission
end
function M.getLux()
local CH0_LOW=readRegister(TSL2561_Address,TSL2561_Channel0L)
local CH0_HIGH=readRegister(TSL2561_Address,TSL2561_Channel0H)
--read two bytes from registers 0x0E and 0x0F
local CH1_LOW=readRegister(TSL2561_Address,TSL2561_Channel1L)
local CH1_HIGH=readRegister(TSL2561_Address,TSL2561_Channel1H)
ch0 = bit.bor(bit.lshift(CH0_HIGH,8),CH0_LOW)
ch1 = bit.bor(bit.lshift(CH1_HIGH,8),CH1_LOW)
end
function M.init(sda, scl)
i2c.setup(id, sda, scl, i2c.SLOW)
writeRegister(TSL2561_Address,TSL2561_Control,0x03) -- POWER UP
writeRegister(TSL2561_Address,TSL2561_Timing,0x00) --No High Gain (1x), integration time of 13ms
writeRegister(TSL2561_Address,TSL2561_Interrupt,0x00)
writeRegister(TSL2561_Address,TSL2561_Control,0x00) -- POWER Down
end
function M.readVisibleLux()
writeRegister(TSL2561_Address,TSL2561_Control,0x03) -- POWER UP
tmr.delay(14000)
M.getLux()
writeRegister(TSL2561_Address,TSL2561_Control,0x00) -- POWER Down
if(ch0/ch1 < 2 and ch0 > 4900) then
return -1 -- ch0 out of range, but ch1 not. the lux is not valid in this situation.
end
return M.calculateLux(0, 0, 0) -- T package, no gain, 13ms
end
function M.calculateLux(iGain, tInt, iType)
if tInt == 0 then -- 13.7 msec
chScale = CHSCALE_TINT0
elseif tInt == 1 then -- 101 msec
chScale = CHSCALE_TINT1
else -- assume no scaling
chScale = bit.lshift(1,CH_SCALE)
end
if (not iGain) then chScale = bit.lshift(chScale,4) end -- scale 1X to 16X
-- scale the channel values
channel0 = bit.rshift((ch0 * chScale),CH_SCALE)
channel1 = bit.rshift((ch1 * chScale),CH_SCALE)
ratio1 = 0
if channel0 ~= 0 then ratio1 = bit.lshift(channel1,(RATIO_SCALE+1))/channel0 end
-- round the ratio value
ratio = bit.rshift((ratio1 + 1),1)
if iType == 0 then -- T package
if ratio >= 0 and ratio <= S.K1T then
b=S.B1T
m=S.M1T
elseif ratio <= S.K2T then
b=S.B2T
m=S.M2T
elseif ratio <= S.K3T then
b=S.B3T
m=S.M3T
elseif ratio <= S.K4T then
b=S.B4T
m=S.M4T
elseif ratio <= S.K5T then
b=S.B5T
m=S.M5T
elseif ratio <= S.K6T then
b=S.B6T
m=S.M6T
elseif ratio <= S.K7T then
b=S.B7T
m=S.M7T
elseif ratio > S.K8T then
b=S.B8T
m=S.M8T
end
elseif iType == 1 then -- CS package
if ratio >= 0 and ratio <= S.K1C then
b=S.B1C
m=S.M1C
elseif ratio <= S.K2C then
b=S.B2C
m=S.M2C
elseif ratio <= S.K3C then
b=S.B3C
m=S.M3C
elseif ratio <= S.K4C then
b=S.B4C
m=S.M4C
elseif ratio <= S.K5C then
b=S.B5C
m=S.M5C
elseif ratio <= S.K6C then
b=S.B6C
m=S.M6C
elseif ratio <= S.K7C then
b=S.B7C
m=S.M7C
end
end
temp=((channel0*b)-(channel1*m))
if temp<0 then temp=0 end
temp = temp + bit.lshift(1,(LUX_SCALE-1))
-- strip off fractional portion
lux = bit.rshift(temp,LUX_SCALE)
return lux
end
return M
# tsl2561 Module
##Require
```lua
tsl2561 = require("tsl2561")
```
## Release
```lua
tsl2561 = nil
package.loaded["tsl2561"]=nil
```
<a id="tsl2561_init"></a>
##init()
####Description
Setting the I2C pin of tsl2561.<br />
####Syntax
init(sda, scl)
####Parameters
sda: 1~12, IO index.<br />
scl: 1~12, IO index.<br />
####Returns
nil
####Example
```lua
SDA_PIN = 6 -- sda pin, GPIO12
SCL_PIN = 5 -- scl pin, GPIO14
tsl2561 = require("tsl2561")
tsl2561.init(SDA_PIN, SCL_PIN)
-- release module
tsl2561 = nil
package.loaded["tsl2561"]=nil
```
####See also
**-** []()
<a id="tsl2561_read"></a>
##readVisibleLux()
####Description
Get the Lux reading of visible light<br />
####Syntax
readVisibleLux()
####Parameters
nil.<br />
####Returns
nil.<br />
####Example
```lua
SDA_PIN = 6 -- sda pin, GPIO12
SCL_PIN = 5 -- scl pin, GPIO14
tsl2561 = require("tsl2561")
tsl2561.init(SDA_PIN, SCL_PIN)
lux = tsl2561.readVisibleLux()
-- release module
tsl2561 = nil
package.loaded["tsl2561"]=nil
```
####See also
**-** []()
-- ***************************************************************************
-- TSL2561 Example Program for ESP8266 with nodeMCU
--
-- Written by Marius Schmeding
--
-- MIT license, http://opensource.org/licenses/MIT
-- ***************************************************************************
tmr.alarm(0, 5000, 1, function()
SDA_PIN = 6 -- sda pin
SCL_PIN = 5 -- scl pin
-- init module
tsl2561 = require("tsl2561")
tsl2561.init(SDA_PIN, SCL_PIN)
-- read value
l = tsl2561.readVisibleLux()
print("lux: "..l.." lx")
-- release module
tsl2561 = nil
package.loaded["tsl2561"]=nil
end)
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment