local i2cslaveaddr = 0x68 --mpu6050
local i2cid = 2
if i2c.setup(i2cid,i2c.SLOW) ~= i2c.SLOW then
log.error("testI2c.init","fail")
return
end
sys.taskInit(function ()
i2c.send(i2cid,i2cslaveaddr,{0X6b,0x80})--复位
sys.wait(100)
i2c.send(i2cid,i2cslaveaddr,{0X6b,0x00})--唤醒
sys.wait(100)
i2c.send(i2cid,i2cslaveaddr,{0x1b,0x80})--陀螺仪传感器±2000dps
i2c.send(i2cid,i2cslaveaddr,{0x1c,0x00})--加速度传感器±2g
i2c.send(i2cid,i2cslaveaddr,{0x19,19})--采样率50hz
i2c.send(i2cid,i2cslaveaddr,{0x38,0x00})--关闭所有中断
i2c.send(i2cid,i2cslaveaddr,{0x6a,0x00})--I2C主模式关闭
i2c.send(i2cid,i2cslaveaddr,{0x23,0x00})--关闭fifo
i2c.send(i2cid,i2cslaveaddr,{0x37,0x80})--int引脚低电平有效
i2c.send(i2cid,i2cslaveaddr,0x75)--读器件地址
local revData = i2c.recv(i2cid,i2cslaveaddr,1)
log.info("i2c read",revData:toHex())
if revData:byte() == 0x68 then
i2c.send(i2cid,i2cslaveaddr,{0x6b,0x01})--设置x轴的pll为参考
i2c.send(i2cid,i2cslaveaddr,{0x6c,0x00})--加速度计与陀螺仪开启
else
log.info("i2c","address not right")
return
end
--处理接收到的数据,变成正确数值
function getTrueData(d)
i2c.send(i2cid,i2cslaveaddr,d)--获取的地址
local s = i2c.recv(i2cid,i2cslaveaddr,2)--获取2字节
return s:byte()*256 + s:byte(2)
end
while true do
sys.wait(50)
local gx = getTrueData(0x43)/131
local gy = getTrueData(0x44)/131
local gz = getTrueData(0x45)/131
log.info("mpu6050.Gyroscope",gx,gy,gz)
local ax = getTrueData(0x3b)/16
local ay = getTrueData(0x3c)/16
local az = getTrueData(0x3d)/16
log.info("mpu6050.Accelerometer",ax,ay,az)
end
end)