Sub topic 9
Reading and writing registers
Most I2C devices work the same way: they expose a small bank of numbered registers, and you read or write those registers to configure the device and collect its data. This chapter shows the byte sequences behind that pattern and the Wire calls that produce them. It also covers the mistakes that cost the most debugging time.
It assumes you can already scan a bus and get an address back, as in the previous chapter. It also assumes you are comfortable with hexadecimal and with bit operations (&, |, <<, >>).
The register model
A register is a byte (sometimes two or more) inside the device, identified by a register address. This is separate from the 7-bit device address. The device address selects the chip on the bus. The register address selects a location inside that chip.
Inside the device, a register pointer holds the register address that the next read or write will use. Every access follows one of two patterns:
- Write: send the device address, the register address, then the data byte(s).
- Read: first write the register address to set the pointer. Then switch direction and read the data back.
The read is two steps because the I2C protocol has no field for a register address. The controller must tell the device which register it wants before it can read anything.
Writing a register
A write is a single transaction. Here is the byte order on the wire:
- START, then the device address with the write bit.
- The register address.
- One or more data bytes.
- STOP.
#include <Wire.h>
// Writes one byte to a register. Returns true if every byte was ACKed.
bool writeRegister8(uint8_t address, uint8_t reg, uint8_t value) {
Wire.beginTransmission(address);
Wire.write(reg);
Wire.write(value);
return Wire.endTransmission() == 0;
}beginTransmission and write only fill a buffer in memory. Nothing is sent until endTransmission runs. That call transmits the whole buffer and returns a status code:
| Code | Meaning |
|---|---|
| 0 | Success, all bytes ACKed |
| 1 | Data too long for the transmit buffer |
| 2 | NACK on the address byte (no device, or wrong address) |
| 3 | NACK on a data byte (the device refused the register or value) |
| 4 | Other error |
| 5 | Timeout (not on every core) |
Check this code every time. Code 2 points to wiring or addressing. Code 3 usually means you wrote to a register the device does not have, or to a read-only one.
Reading a register
A read combines a short write with a read. The key detail is how the first part ends.
#include <Wire.h>
// Reads one byte from a register. Returns true on success.
bool readRegister8(uint8_t address, uint8_t reg, uint8_t &value) {
Wire.beginTransmission(address);
Wire.write(reg);
if (Wire.endTransmission(false) != 0) { // false: no STOP, send a repeated START next
return false;
}
if (Wire.requestFrom(address, (uint8_t)1) != 1) {
return false;
}
value = Wire.read();
return true;
}endTransmission(false) sends the register address but skips the STOP. The following requestFrom then begins with a repeated START, so the controller keeps ownership of the bus between the two halves. The device holds its register pointer in place until the read arrives.
Notice the controller's NACK on the last byte. It is not an error. It tells the target to stop sending, so the controller can then issue a STOP. requestFrom does this for you.
If endTransmission() is called with no argument, or with true, it sends a STOP. A few devices need that STOP between the pointer write and the read. Most accept either form. If a read returns stale or constant data, try the other form.
Multi-byte values and endianness
Many registers hold 16-bit values, and the datasheet says which byte comes first. Big-endian devices send the high byte first. Some devices, such as certain accelerometers, send the low byte first. Assembling the bytes in the wrong order gives plausible-looking but wrong numbers, so check the datasheet before you write the shift.
#include <Wire.h>
// Reads a 16-bit big-endian register from a device.
// Returns true on success and stores the result in value.
bool readRegister16(uint8_t address, uint8_t reg, uint16_t &value) {
Wire.beginTransmission(address);
Wire.write(reg);
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;
}Signed values need one more step. Cast the assembled word to int16_t before you scale it. Otherwise a negative reading shows up as a large positive number.
A complete example: reading a temperature sensor
The TMP102 sensor sits at address 0x48 by default. Its temperature register is at pointer 0x00. It returns 12 bits of two's-complement data, left-aligned in 16 bits, at 0.0625 °C per step. The sketch below reads it once a second.
#include <Wire.h>
const uint8_t SENSOR_ADDRESS = 0x48;
const uint8_t REG_TEMPERATURE = 0x00;
bool readRegister16(uint8_t address, uint8_t reg, uint16_t &value) {
Wire.beginTransmission(address);
Wire.write(reg);
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();
}
void loop() {
uint16_t raw;
if (readRegister16(SENSOR_ADDRESS, REG_TEMPERATURE, raw)) {
int16_t counts = (int16_t)raw >> 4; // signed shift keeps the sign
Serial.print("Temperature: ");
Serial.print(counts * 0.0625, 2);
Serial.println(" C");
} else {
Serial.println("Read failed");
}
delay(1000);
}If you use a different sensor, change the address, register, and conversion to match its datasheet. The read pattern stays the same.
Reading several registers in one transaction
Many devices auto-increment the register pointer after each byte. You can then read a block of consecutive registers in one transaction. This is faster than separate reads, and it guarantees the values were captured together. That matters for an accelerometer's X, Y, and Z registers.
#include <Wire.h>
// Reads count consecutive bytes starting at reg. Returns true if all arrived.
bool readBlock(uint8_t address, uint8_t reg, uint8_t *buffer, uint8_t count) {
Wire.beginTransmission(address);
Wire.write(reg);
if (Wire.endTransmission(false) != 0) {
return false;
}
if (Wire.requestFrom(address, count) != count) {
return false;
}
for (uint8_t i = 0; i < count; i++) {
buffer[i] = Wire.read();
}
return true;
}Whether auto-increment happens, and whether it needs a flag bit set in the register address, depends on the device. Some parts require you to set the top bit of the pointer byte. Check the datasheet before relying on it.
Changing part of a register: read-modify-write
Configuration registers pack several settings into one byte. To change one field without disturbing the others, read the register, change only the bits you want, then write it back.
#include <Wire.h>
bool readRegister8(uint8_t address, uint8_t reg, uint8_t &value);
bool writeRegister8(uint8_t address, uint8_t reg, uint8_t value);
// Sets the bits selected by mask to the matching bits of bits.
bool updateBits(uint8_t address, uint8_t reg, uint8_t mask, uint8_t bits) {
uint8_t current;
if (!readRegister8(address, reg, current)) {
return false;
}
current = (current & ~mask) | (bits & mask);
return writeRegister8(address, reg, current);
}This snippet uses the two helpers defined earlier in the chapter. Put all the helpers in one sketch. Some registers are write-only or have bits that clear when read, so check how the datasheet describes them before you read-modify-write.
Common errors
- Casting
requestFromarguments. Passing a plainintfor the byte count can pick the wrong overload on some cores. Cast the count touint8_t, as the examples do. - Ignoring return values. A failed
endTransmissionor a shortrequestFromleaves you reading zeros or stale buffer data. Branch on the result. - Exceeding the buffer. The Wire buffer is 32 bytes on AVR boards. The register byte counts toward that limit on a write, and a long read is truncated. Split larger transfers.
- Skipping conversion time. Some sensors need a delay after you start a measurement before the result register is valid. Read too soon and you get the previous sample.
- Mixing up addresses. Datasheets sometimes list 8-bit addresses with the read/write bit included. Wire expects the 7-bit form, so shift an 8-bit value right by one.
- Wide register addresses. Devices such as I2C EEPROMs use 16-bit internal addresses. Send the high byte first, then the low byte, before reading or writing data.
Exercise
Why does a register read call endTransmission(false) instead of endTransmission(), and what happens on the bus as a result?
Show answer
Passing false suppresses the STOP condition after the register address is sent. The following requestFrom then starts with a repeated START, so the controller keeps the bus and the device's register pointer stays where it was set. A plain endTransmission() sends a STOP first. That works on many devices, but some need the STOP and others need the repeated START, so use whichever form the datasheet expects.
Exercise
A sensor returns its 16-bit reading as two bytes, high byte first. The value is two's complement. Write the expression that turns the two bytes hi and lo into a signed integer.
Show answer
int16_t value = (int16_t)(((uint16_t)hi << 8) | lo); Casting to int16_t after combining the bytes lets negative readings come out negative.