Sub topic 5
Anatomy of an I2C Transaction
Assume you know basic Arduino sketches, hexadecimal numbers, and how to use the Serial Monitor. This chapter focuses on what happens on the two-wire bus during one I2C transaction.
The transaction sequence
An I2C transaction is a controlled exchange between one controller, such as an Arduino, and a target device, such as a sensor. The controller creates the clock on SCL. Both devices use SDA to exchange data.
A typical transaction follows this pattern:
- The controller sends a START condition.
- It sends the target's 7-bit address plus one read/write bit.
- The target returns an ACK, or acknowledge bit.
- The controller and target exchange one or more data bytes.
- The receiver sends ACK after each byte it accepts.
- The controller sends STOP, releasing the bus.
A START occurs when SDA falls while SCL is high. A STOP occurs when SDA rises while SCL is high. These transitions are special because normal data changes happen while SCL is low.
ACK, NACK, and repeated START
Each byte contains eight data bits. The ninth clock pulse is used for acknowledgment. The receiver pulls SDA low for an ACK. It leaves SDA high for a NACK, meaning “I did not accept another byte” or “the transfer is finished.”
A read often begins with a write. The controller first writes a register number, then changes direction and reads the register value. A repeated START begins the second part without sending STOP. This keeps control of the bus between the two operations.
The Arduino Wire library represents these phases directly:
#include <Wire.h>
const uint8_t SENSOR_ADDRESS = 0x48;
const uint8_t REGISTER_NUMBER = 0x00;
void setup() {
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(SENSOR_ADDRESS);
Wire.write(REGISTER_NUMBER);
if (Wire.endTransmission(false) != 0) {
Serial.println("Target did not acknowledge the register request");
return;
}
uint8_t received = Wire.requestFrom(SENSOR_ADDRESS, (uint8_t)1);
if (received == 1 && Wire.available()) {
Serial.println(Wire.read());
} else {
Serial.println("Read failed");
}
}
void loop() {}The false argument prevents endTransmission from sending STOP. requestFrom then sends a repeated START and changes the direction to read. A successful endTransmission returns zero when the target acknowledges the address and written bytes.
Exercise
Why does a register read commonly use a repeated START instead of STOP followed by a new transaction?
Show answer
The repeated START keeps control of the bus while the controller changes from writing the register number to reading its value.