-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmcp9804.lua
46 lines (40 loc) · 977 Bytes
/
mcp9804.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
-- MCP9804 module
--
-- usage:
-- mcp9804 = dofile('mcp9804.lua')
-- mcp9804.init(sda_pin, scl_pin)
-- temperature = mcp9804.read(addr)
--
local M
do
--I2C init
local id = 0
local init_i2c = function(sda, scl)
i2c.setup(id,sda, scl, i2c.SLOW)
end
-- Function to read temperature
local read_temp = function(addr)
local temp = read_reg(addr, 0x05)
temp = 256 * string.byte(temp,1) + string.byte(temp,2)
temp = bit.clear(temp,13,14,15)
temp = temp * 0.0625
return temp
end
function read_reg(addr, reg)
local val
i2c.start(id)
i2c.address(id, addr, i2c.TRANSMITTER)
i2c.write(id, reg)
i2c.stop(id)
i2c.start(id)
i2c.address(id, addr, i2c.RECEIVER)
val = i2c.read(id, 2)
i2c.stop(id)
return val
end
M = {
read = read_temp,
init = init_i2c
}
end
return M