Sub topic 9
Reading and Writing I2C Device Registers
This chapter assumes you understand Arduino setup() and loop(), hexadecimal numbers, and the basic I2C transaction. A register is a small storage location inside an I2C device. Sensors often use registers for configuration, status, and measurement data.
The register-access pattern
Most register-based devices use this sequence:
- The controller sends the target address with the write bit.
- The controller sends the register number.
- The controller sends one or more data bytes for a write, or changes direction for a read.
- The target acknowledges each byte.
- The controller ends the transaction with a STOP condition.
To read, the controller usually writes the register number first. It then sends a repeated START and requests data without releasing the bus between operations.
Reading a 16-bit register
The following helper reads two bytes from a register. It assumes the device sends the most significant byte first, which is called big-endian order. The register map for your device may use a different byte order or data length.
#include <Wire.h>
const uint8_t DEVICE_ADDRESS = 0x68;
bool readRegister16(uint8_t address, uint8_t reg, uint16_t &value) {
Wire.beginTransmission(address);
Wire.write(reg);
// Keep control of the bus for the repeated START.
if (Wire.endTransmission(false) != 0) {
return false;
}
if (Wire.requestFrom(address, (uint8_t)2) != 2) {
return false;
}
value = (uint16_t)Wire.read() << 8;
value |= Wire.read();
return true;
}
void setup() {
Serial.begin(9600);
Wire.begin();
uint16_t value;
if (readRegister16(DEVICE_ADDRESS, 0x00, value)) {
Serial.print("Register value: 0x");
Serial.println(value, HEX);
} else {
Serial.println("I2C read failed");
}
}
void loop() {
}endTransmission(false) sends the register pointer but does not send STOP. The next operation starts with a repeated START. Passing true, or omitting the argument, usually releases the bus first.
Writing a register
A register write sends the register number followed by its new value.
void writeRegister8(uint8_t address, uint8_t reg, uint8_t value) {
Wire.beginTransmission(address);
Wire.write(reg);
Wire.write(value);
byte error = Wire.endTransmission();
if (error != 0) {
Serial.println("I2C write failed");
}
}The meaning of each register and value comes from the device data sheet. Some devices require a delay after a write, a specific initialization order, or a checksum.
| Operation | Typical Wire calls | Bus result |
|---|---|---|
| Write register | `beginTransmission`, `write`, `endTransmission` | Register number and data are sent |
| Read register | `write` register, `endTransmission(false)`, `requestFrom` | Register pointer is followed by returned bytes |
Exercise
Why is endTransmission(false) useful when reading a register?
Show answer
It keeps the bus active so the controller can issue a repeated START and request data from the selected register.