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