connection_check.ino 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "MPU9250.h"
  2. uint8_t addrs[7] = {0};
  3. uint8_t device_count = 0;
  4. template <typename WireType = TwoWire>
  5. void scan_mpu(WireType& wire = Wire) {
  6. Serial.println("Searching for i2c devices...");
  7. device_count = 0;
  8. for (uint8_t i = 0x68; i < 0x70; ++i) {
  9. wire.beginTransmission(i);
  10. if (wire.endTransmission() == 0) {
  11. addrs[device_count++] = i;
  12. delay(1);
  13. }
  14. }
  15. Serial.print("Found ");
  16. Serial.print(device_count, DEC);
  17. Serial.println(" I2C devices");
  18. Serial.print("I2C addresses are: ");
  19. for (uint8_t i = 0; i < device_count; ++i) {
  20. Serial.print("0x");
  21. Serial.print(addrs[i], HEX);
  22. Serial.print(" ");
  23. }
  24. Serial.println();
  25. }
  26. template <typename WireType = TwoWire>
  27. uint8_t readByte(uint8_t address, uint8_t subAddress, WireType& wire = Wire) {
  28. uint8_t data = 0;
  29. wire.beginTransmission(address);
  30. wire.write(subAddress);
  31. wire.endTransmission(false);
  32. wire.requestFrom(address, (size_t)1);
  33. if (wire.available()) data = wire.read();
  34. return data;
  35. }
  36. void setup() {
  37. Serial.begin(115200);
  38. Serial.flush();
  39. Wire.begin();
  40. delay(2000);
  41. scan_mpu();
  42. if (device_count == 0) {
  43. Serial.println("No device found on I2C bus. Please check your hardware connection");
  44. while (1)
  45. ;
  46. }
  47. // check WHO_AM_I address of MPU
  48. for (uint8_t i = 0; i < device_count; ++i) {
  49. Serial.print("I2C address 0x");
  50. Serial.print(addrs[i], HEX);
  51. byte c = readByte(addrs[i], WHO_AM_I_MPU9250);
  52. if (c == MPU9250_WHOAMI_DEFAULT_VALUE) {
  53. Serial.println(" is MPU9250 and ready to use");
  54. } else if (c == MPU9255_WHOAMI_DEFAULT_VALUE) {
  55. Serial.println(" is MPU9255 and ready to use");
  56. } else {
  57. Serial.println(" is not MPU series. Please use correct device");
  58. }
  59. }
  60. }
  61. void loop() {
  62. }