-
Notifications
You must be signed in to change notification settings - Fork 1
/
hmc5883l.lua
118 lines (108 loc) · 2.67 KB
/
hmc5883l.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
------------------------------------------------------------------------------
-- HMC5883L query module
--
-- dofile("hmc5883l2.lua").help()
--
-- hmc = dofile("hmc5883l.lua")
-- isok = hmc.init(sda, scl)
--isok = hmc.init(1,2)
-- r= hmc.read()
--=r.x
--compass_tmr=tmr.create()
--compass_tmr:register(300, tmr.ALARM_AUTO, function(t)
-- compass= hmc.read()
--print("x:"..compass.x.."\ny:"..compass.y)
--end)
--compass_tmr:start()
--sda, scl = 1, 2
--i2c.setup(0, sda, scl, i2c.SLOW) -- call i2c.setup() only once
--hmc5883l.setup()
--compass_tmr=tmr.create()
--compass_tmr:register(300, tmr.ALARM_AUTO, function(t)
--x,y,z = hmc5883l.read()
--print(string.format("x = %d, y = %d, z = %d", x*0.92, z*0.92, y*0.92))
--end)
--compass_tmr:start()
--
------------------------------------------------------------------------------
local M
do
-- cache
local i2c, print = i2c, print
-- helpers
local r8 = function(reg)
i2c.start(0)
i2c.address(0, 0x1E, i2c.TRANSMITTER)
i2c.write(0, reg)
i2c.stop(0)
i2c.start(0)
i2c.address(0, 0x1E, i2c.RECEIVER)
local r = i2c.read(0, 1)
i2c.stop(0)
print(r:byte(1))
return r:byte(1)
end
local w8 = function(reg, val)
i2c.start(0)
i2c.address(0, 0x1E, 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
-- gain
local gain = 0x20
-- hmc.help
local help = function()
print("HMC5883L query module")
print(" dofile(\"hmc5883l.lua\").help()")
print(" hmc = dofile(\"hmc5883l.lua\")")
print(" isok = hmc.init(sda, scl)")
print(" {x, y, z} = hmc.read()")
end
-- hmc.init
local init = function(sda, scl)
i2c.setup(0, sda, scl, i2c.SLOW)
-- check id
if r8(0x0A) == 0x48 and r8(0x0B) == 0x34 and r8(0x0C) == 0x33 then
-- data output rate and samples num = 1sample @ 75Hz
w8(0x00, 0x18)
-- device gain = 0.92mG/LSb
w8(0x01, gain)
-- operating mode = continious
w8(0x02, 0x00)
print("read ok")
return true
else
return false
end
end
-- hmc.read
local read = function()
-- Gausses
local result = {}
print("read start")
if gain == 0x20 then
result.x = r16(0x03)*0.92
result.y = r16(0x07)*0.92
result.z = r16(0x05)*0.92
print("read done")
end
print(result)
return result
end
-- expose
M = {
help = help,
init = init,
read = read,
}
end
return M