3 @summary qmc5883l 地磁传感器
6 @author Dozingfiretruck
8 --注意:因使用了sys.wait()所有api需要在协程中使用
10 local qmc5883l = require "qmc5883l"
13 sys.taskInit(function()
14 i2c.setup(i2cid,i2c_speed)
15 qmc5883l.init(i2cid)--初始化,传入i2c_id
17 local qmc5883l_data = qmc5883l.get_data()
18 log.info("qmc5883l_data", qmc5883l_data.x,qmc5883l_data.y,qmc5883l_data.z,qmc5883l_data.heading,qmc5883l_data.headingDegrees)
26 local sys
= require
"sys"
29 local QMC5883L_ADDRESS_ADR
31 local QMC5883L_ADDRESS_ADR_LOW
= 0x0C
32 local QMC5883L_ADDRESS_ADR_HIGH
= 0x0D
34 local QMC5883L_CHIP_ID_CHECK
= 0x0D
35 local QMC5883L_CHIP_ID
= 0xFF
39 local QMC5883L_X_LSB
= 0x00
40 local QMC5883L_X_MSB
= 0x01
41 local QMC5883L_Y_LSB
= 0x02
42 local QMC5883L_Y_MSB
= 0x03
43 local QMC5883L_Z_LSB
= 0x04
44 local QMC5883L_Z_MSB
= 0x05
45 local QMC5883L_STATUS
= 0x06
46 local QMC5883L_T_LSB
= 0x07
47 local QMC5883L_T_MSB
= 0x08
48 local QMC5883L_CONTROL1
= 0x09
49 local QMC5883L_CONTROL2
= 0x0A
50 local QMC5883L_PERIOD
= 0x0B
53 local function chip_check()
54 i2c
.send(i2cid
, QMC5883L_ADDRESS_ADR_HIGH
, QMC5883L_CHIP_ID_CHECK
)--读器件地址
55 local revData
= i2c
.recv(i2cid
, QMC5883L_ADDRESS_ADR_HIGH
, 1)
56 if revData
:byte() ~= nil then
57 QMC5883L_ADDRESS_ADR
= QMC5883L_ADDRESS_ADR_HIGH
59 i2c
.send(i2cid
, QMC5883L_ADDRESS_ADR_LOW
, QMC5883L_CHIP_ID_CHECK
)--读器件地址
61 local revData
= i2c
.recv(i2cid
, QMC5883L_ADDRESS_ADR_LOW
, 1)
62 if revData
:byte() ~= nil then
63 QMC5883L_ADDRESS_ADR
= QMC5883L_ADDRESS_ADR_LOW
65 log.info("Can't find QMC5883L device")
70 i2c
.send(i2cid
, QMC5883L_ADDRESS_ADR
, QMC5883L_CHIP_ID_CHECK
)--读器件地址
71 local revData
= i2c
.recv(i2cid
, QMC5883L_ADDRESS_ADR
, 1)
72 if revData
:byte() == QMC5883L_CHIP_ID
then
73 log.info("Device i2c id is: QMC5883L")
76 log.info("Can't find QMC5883L device")
83 @api qmc5883l.init(i2c_id)
89 function qmc5883l
.init(i2c_id
)
92 i2c
.send(i2cid
, QMC5883L_ADDRESS_ADR
, {QMC5883L_PERIOD
,0x01})
93 i2c
.send(i2cid
, QMC5883L_ADDRESS_ADR
, {QMC5883L_CONTROL1
,0x1D})
100 @api qmc5883l.get_data()
101 @return table qmc5883l 数据
103 local qmc5883l_data = qmc5883l.get_data()
104 log.info("qmc5883l_data", qmc5883l_data.x,qmc5883l_data.y,qmc5883l_data.z,qmc5883l_data.heading,qmc5883l_data.headingDegrees)
106 function qmc5883l
.get_data()
107 local qmc5883l_data
= {}
108 i2c
.send(i2cid
, QMC5883L_ADDRESS_ADR
,QMC5883L_X_LSB
)
109 local data
= i2c
.recv(i2cid
, QMC5883L_ADDRESS_ADR
, 6)
110 _
, qmc5883l_data
.x
, qmc5883l_data
.y
, qmc5883l_data
.z
= pack
.unpack(data
, "<h3")
111 local heading
= math
.atan (qmc5883l_data
.y
,qmc5883l_data
.x
)
112 qmc5883l_data
.heading
= heading
113 local declinationAngle
= 0.0404
114 heading
= heading
+declinationAngle
115 if heading
< 0 then heading
= heading
+2*math
.pi
end
116 if heading
> 2*math
.pi
then heading
= heading
-2*math
.pi
end
117 qmc5883l_data
.headingDegrees
= heading
* 180/math
.pi