i2c_readwrite.ino 1.0 KB

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