![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
MPU-6050 sample code
Diff: mpu6050.cpp
- Revision:
- 1:6f743fe9a027
- Parent:
- 0:abd3a0fd55a9
- Child:
- 3:ebd656a9c89f
--- a/mpu6050.cpp Wed Dec 12 12:42:30 2018 +0000 +++ b/mpu6050.cpp Thu Dec 13 03:00:27 2018 +0000 @@ -1,23 +1,22 @@ #include "mpu6050.h" -DigitalOut led(LED3); - -static double RATE_ACC_LIST[4] = { +static const double RATE_ACC_LIST[4] = { 16384.0, 8192.0, 4096.0, 2048.0, }; -static double RATE_GYRO_LIST[4] = { +static const double RATE_GYRO_LIST[4] = { 131.0, 65.5, 32.8, 16.4, }; -MPU6050::MPU6050(PinName i2c_sda, PinName i2c_scl) : i2c(i2c_sda, i2c_scl), address(208), rate_accelemeter(16384.0), rate_gyroscope(131.0) +MPU6050::MPU6050(PinName i2c_sda, PinName i2c_scl) : i2c(i2c_sda, i2c_scl), address(0x68 << 1), rate_accelemeter(16384.0), rate_gyroscope(131.0) { + setSleep(false); setMaxScale(MAX_ACC_2G, MAX_GYRO_250degpersec); } @@ -30,15 +29,11 @@ int result_write = i2c.write(address, ®, 1); if(result_write) { // failed - //pc.printf("i2c error\r\n"); - led = 1; } char read_data; int result_read = i2c.read(address, &read_data, 1); if(result_read) { // failed - //pc.printf("i2c error\r\n"); - led = 1; } return read_data; } @@ -51,8 +46,6 @@ int result = i2c.write(address, buf, 2); if(result) { // failed - //pc.printf("i2c error\r\n"); - led = 1; } } @@ -62,7 +55,7 @@ short x, y, z; // read X h = readByte(0x3B); - l = readByte(0x3C); + l = readByte(0x75); x = h << 8 | l; // read Y h = readByte(0x3D); @@ -140,3 +133,16 @@ } rate_gyroscope = RATE_GYRO_LIST[max_gyro]; } + +void MPU6050::setSleep(bool sleep) +{ + const char reg_sleep = 0x6B; + const char current_state = readByte(reg_sleep); + char write_data; + if(sleep) { + write_data = current_state | 0x40; + } else { + write_data = current_state & (~0x40); + } + writeByte(reg_sleep, write_data); +}