mpu6050.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* Copyright (c) 2009 Nordic Semiconductor. All Rights Reserved.
  2. *
  3. * The information contained herein is property of Nordic Semiconductor ASA.
  4. * Terms and conditions of usage are described in detail in NORDIC
  5. * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
  6. *
  7. * Licensees are granted free, non-transferable use of the information. NO
  8. * WARRANTY of ANY KIND is provided. This heading must NOT be removed from
  9. * the file.
  10. *
  11. */
  12. #include <stdbool.h>
  13. #include <stdint.h>
  14. #include "twi_master.h"
  15. #include "mpu6050.h"
  16. /*lint ++flb "Enter library region" */
  17. #define ADDRESS_WHO_AM_I (0x75U) // !< WHO_AM_I register identifies the device. Expected value is 0x68.
  18. #define ADDRESS_SIGNAL_PATH_RESET (0x68U) // !<
  19. static const uint8_t expected_who_am_i = 0x68U; // !< Expected value to get from WHO_AM_I register.
  20. static uint8_t m_device_address; // !< Device address in bits [7:1]
  21. bool mpu6050_init(uint8_t device_address)
  22. {
  23. bool transfer_succeeded = true;
  24. m_device_address = (uint8_t)(device_address << 1);
  25. // Do a reset on signal paths
  26. uint8_t reset_value = 0x04U | 0x02U | 0x01U; // Resets gyro, accelerometer and temperature sensor signal paths.
  27. transfer_succeeded &= mpu6050_register_write(ADDRESS_SIGNAL_PATH_RESET, reset_value);
  28. // Read and verify product ID
  29. transfer_succeeded &= mpu6050_verify_product_id();
  30. return transfer_succeeded;
  31. }
  32. bool mpu6050_verify_product_id(void)
  33. {
  34. uint8_t who_am_i;
  35. if (mpu6050_register_read(ADDRESS_WHO_AM_I, &who_am_i, 1))
  36. {
  37. if (who_am_i != expected_who_am_i)
  38. {
  39. return false;
  40. }
  41. else
  42. {
  43. return true;
  44. }
  45. }
  46. else
  47. {
  48. return false;
  49. }
  50. }
  51. bool mpu6050_register_write(uint8_t register_address, uint8_t value)
  52. {
  53. uint8_t w2_data[2];
  54. w2_data[0] = register_address;
  55. w2_data[1] = value;
  56. return twi_master_transfer(m_device_address, w2_data, 2, TWI_ISSUE_STOP);
  57. }
  58. bool mpu6050_register_read(uint8_t register_address, uint8_t * destination, uint8_t number_of_bytes)
  59. {
  60. bool transfer_succeeded;
  61. transfer_succeeded = twi_master_transfer(m_device_address, &register_address, 1, TWI_DONT_ISSUE_STOP);
  62. transfer_succeeded &= twi_master_transfer(m_device_address|TWI_READ_BIT, destination, number_of_bytes, TWI_ISSUE_STOP);
  63. return transfer_succeeded;
  64. }
  65. /*lint --flb "Leave library region" */