i2c_readwrite.ino 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include <Adafruit_I2CDevice.h>
  2. #define I2C_ADDRESS 0x60
  3. Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(I2C_ADDRESS);
  4. void setup() {
  5. while (!Serial) {
  6. delay(10);
  7. }
  8. Serial.begin(115200);
  9. Serial.println("I2C device read and write test");
  10. if (!i2c_dev.begin()) {
  11. Serial.print("Did not find device at 0x");
  12. Serial.println(i2c_dev.address(), HEX);
  13. while (1)
  14. ;
  15. }
  16. Serial.print("Device found on address 0x");
  17. Serial.println(i2c_dev.address(), HEX);
  18. uint8_t buffer[32];
  19. // Try to read 32 bytes
  20. i2c_dev.read(buffer, 32);
  21. Serial.print("Read: ");
  22. for (uint8_t i = 0; i < 32; i++) {
  23. Serial.print("0x");
  24. Serial.print(buffer[i], HEX);
  25. Serial.print(", ");
  26. }
  27. Serial.println();
  28. // read a register by writing first, then reading
  29. buffer[0] = 0x0C; // we'll reuse the same buffer
  30. i2c_dev.write_then_read(buffer, 1, buffer, 2, false);
  31. Serial.print("Write then Read: ");
  32. for (uint8_t i = 0; i < 2; i++) {
  33. Serial.print("0x");
  34. Serial.print(buffer[i], HEX);
  35. Serial.print(", ");
  36. }
  37. Serial.println();
  38. }
  39. void loop() {}