raspberrypi / pico-examples

BSD 3-Clause "New" or "Revised" License
2.63k stars 781 forks source link

MPU6050 i2c example expanded into library #504

Open NirajPatelRobots opened 2 weeks ago

NirajPatelRobots commented 2 weeks ago

I refactored and expanded the mpu6050_i2c example. This adds new functions for MPU6050 features and clarifies existing ones. It also refactors the example into an MPU6050_i2c library and main.c. There are C and C++ versions of the library. I've been using the C++ library in another project for around a year.

I realize that this is a pretty drastic change, and moves the code away from its original intent as a pico code example. I plan on separating this into a dedicated mpu6050_i2c pico library. However, some of these changes could be useful for the pico-examples repo. Some possibilities are:

I'm happy to include any suggestions you have.

peterharperuk commented 2 weeks ago

Thanks. I have a so far untested MPU6050, I'll give it a go.

lurch commented 2 weeks ago

Presumably this also fixes / supersedes the issues identified with the current example code? https://github.com/raspberrypi/pico-examples/issues?q=is%3Aopen+MPU6050

NirajPatelRobots commented 1 week ago

@lurch , Several issues are related to the DEVICE_RESET value. The original example used 0x6B 0x00 in mpu6050_reset(). The register map says to set DEVICE_RESET =1 (0x6B 0x80) to reset the registers, so https://github.com/raspberrypi/pico-examples/pull/319 implemented that. However, https://github.com/raspberrypi/pico-examples/issues/352 and https://github.com/raspberrypi/pico-examples/pull/494 reported that the example didn't work after https://github.com/raspberrypi/pico-examples/pull/319 was merged. The discussion in 319 eventually determined that 0x80 is resetting the MPU6050, which causes the MPU6050 to enter sleep mode, which explains why the example stopped working. Several commenters in https://github.com/raspberrypi/pico-examples/pull/319 suggest writing DEVICE_RESET =1, waiting, then setting the register to 0x00 again. That works because DEVICE_RESET and SLEEP are in the same register, so sleep mode is disabled. I added a mpu6050_power() function after mpu6050_reset() to exit sleep mode.

NirajPatelRobots commented 1 week ago

I've pushed some changes to improve it, including adding a test that demonstrates scaling with the C++ library. Unfortunately, my pico has stopped working, so I can't test it myself.