Module 5 · Lesson 57 of 129

The I2C bus and driver core

Explain I2C signaling and addressing, then trace how Linux registers an I2C driver and binds it to a device.

  • Beginner to advanced
  • 8 min read
  • 11 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM for written practice. No I2C board is required.

Your place in the module
By the end you can 4 objectives
  • Decode the address, direction and acknowledgment in a 7-bit I2C transaction.
  • Explain how the bus clock rate and clock stretching affect a transaction.
  • Distinguish an I2C adapter, client and driver in the Linux device model.
  • Trace registration, matching, probe and removal for an I2C driver.
Video coming soonThe I2C bus and driver core
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Userspace tools for input and LEDs
  • evtest reads input events from a selected /dev/input/event* node.
  • An EV_KEY event value of 1 means press, 0 means release, and 2 means repeat.
  • Square brackets in the trigger attribute identify the active selection.
01

What happens on SDA and SCL

4 min read

The last lesson closed with userspace tools for input and LEDs. This lesson answers the I2C bus those sensor drivers will use, its addressing and clock stretching, and how the i2c_driver and i2c_client model it.

A controller can put an address on the wires and receive no acknowledgment. Linux documents this as a failure at the address phase, which an adapter can report as -ENXIO. That failure tells you where communication stopped. To interpret it, first identify who sends the address, who drives the acknowledgment, and when each line changes. I2C fault codes

SDA is the serial data line. SCL is the serial clock line. The controller initiates the transaction and generates the clock. The addressed device is the target. Both wires use open-drain signaling in the modes covered here. A device can pull a line low or release it. A pull-up resistor brings the line high when every device releases it. If any device still pulls the line low, it stays low. An idle bus has both lines high.

A START occurs when the controller pulls SDA low while SCL is high. A STOP occurs when SDA rises while SCL is high. During ordinary data bits, the transmitter sets SDA while SCL is low and keeps it stable while SCL is high so the receiver can sample it. The two transitions during SCL high are deliberate signals that mark transaction boundaries. The controller can also issue a repeated START while retaining control of the bus between phases.

One-byte I2C writeSTARTSDA falls,SCL highAddress andwrite bitControllertransmitsAddress ACKTargetpulls SDAlowData byteControllertransmitsData ACKTargetpulls SDAlowSTOPSDA rises,SCL highSTARTSDA falls,SCL highAddress andwrite bitControllertransmitsAddress ACKTargetpulls SDAlowData byteControllertransmitsData ACKTargetpulls SDAlowSTOPSDA rises,SCL high
A 7-bit write with one data byte and an acknowledgment after each byte

In a 7-bit transaction, the first byte carries the seven address bits, most significant bit first, followed by the direction bit. A direction bit of zero means write, and one means read. The receiver signals ACK by pulling SDA low on the ninth clock. The transmitter releases SDA for that clock. If SDA stays high, the result is NACK. During a write, the target acknowledges the address and the data bytes. During a read, the target acknowledges the address, then transmits data. The controller acknowledges each byte it wants to continue reading after and sends a NACK after the final byte before ending the read with a STOP or proceeding with a repeated START.

A datasheet may print separate write and read values that already include the direction bit. If those values are 0xA0 and 0xA1, the 7-bit address is 0x50, obtained by shifting either value right by one bit. Linux stores 0x50 in the client's address field in that example. If the datasheet already gives the address as 0x50, use it directly. These values illustrate the encoding, so the same arithmetic applies when the address differs.

10-bit addressing uses a distinct wire format. The first address byte begins with the reserved prefix 11110, followed by the two high address bits and a zero direction bit. The next byte carries the eight low address bits. For a read, the controller first sends those two bytes, then issues a repeated START and sends the first address byte again with the direction bit set to one. The controller and target must support this format. Linux represents a 10-bit client's address with its full value and the I2C_CLIENT_TEN flag in client->flags.

02

Bus speed and clock stretching

3 min read

The usual speed grades are Standard-mode up to 100 kbit/s, Fast-mode up to 400 kbit/s, and Fast-mode Plus up to 1 Mbit/s. These limits correspond to SCL rates of 100 kHz, 400 kHz and 1 MHz. The adapter generates the clock, and the selected rate must suit the controller, the devices on the bus and the board wiring. The rate describes signaling. Address bytes and ACK clocks occupy time too, so the rate of payload delivery is lower.

The pull-ups and the bus capacitance affect how quickly each released line reaches a valid high level. A line can reach high during the longer clock period at Standard-mode and rise too slowly at Fast-mode on the same wiring. When comparing a configured rate with a logic capture, check the timing of the actual line transitions. The controller can release SCL before the line has physically reached a valid high level.

A target may also deliberately hold SCL low after the controller releases it. This is . A controller that supports stretching waits for SCL to go high before continuing. When the target releases SCL, the pull-up raises the line and the transfer resumes. A long low phase delays the transfer even when the nominal bus rate stays the same. An ACK uses SDA on the ninth clock. Stretching uses SCL and extends a low phase.

One stretched clockTargetholds SCLControllerreleasesSCLSCL stayslowControllerwaitsTargetreleasesSCLSCL risesTransfercontinuesTargetholds SCLControllerreleasesSCLSCL stayslowControllerwaitsTargetreleasesSCLSCL risesTransfercontinues
The controller releases SCL, and the target determines when the stretched low phase ends
Going deeperClock-stretching timeouts and bus recovery

A controller or adapter driver can enforce a finite wait. If a target holds SCL beyond that limit, the adapter can abort the transfer and report -ETIMEDOUT. The limit and the circumstances that produce this error depend on the adapter implementation. A timeout alone does not tell you whether SCL stayed low, SDA stayed low, or the controller failed to finish for another reason.

One recoverable condition occurs when a transfer is interrupted and the target still holds SDA low while waiting for more clocks. An adapter with suitable board wiring can configure struct i2c_bus_recovery_info to let the Linux I2C core use i2c_generic_scl_recovery(). The recovery setup can use a GPIO for SCL, with the pins switched to their recovery function when needed. The routine can try up to nine SCL pulses. It drives SCL low and releases it for each high phase, giving the target a chance to finish the byte and release SDA. With SDA control available, the routine also attempts STOP conditions. After recovery the adapter can restore normal pin control.

This relies on SCL actually rising when released. If a target holds SCL low or the wire is shorted to ground, GPIO clock pulses cannot clear the bus. Recovery belongs to the adapter because it owns the shared wires and their pin configuration. The client driver's transfer can still fail even when the bus has been made available for a later transaction.

03

Registering and binding an I2C driver

4 min read

Linux represents an I2C bus with struct i2c_adapter. The adapter provides access to the bus and is usually registered by the controller driver. A struct i2c_client represents one device on that adapter. Its adapter field identifies the bus, addr holds the device address, and dev is the embedded device-model object. Two different adapters can each have a client at 0x50. The adapter identifies which bus Linux must use to reach each one.

On a Device Tree board, an enabled child node under the I2C controller can describe a client. The child's reg supplies its bus address and its compatible identifies the device model. When the adapter is registered and the core processes the child node, Linux can create the client from that description. A client object therefore means Linux has a device description at a particular bus address. Creation of the object does not depend on an electrical acknowledgment from the target. If the device is absent or unpowered, the object can still exist.

Matching and bindingClient anddriverBothregistered,eitherorderMatchclientForexample,comparecompatiblestringsCall probePass theclientpointerBind clientProbereturnedzeroExit from step 3: Negative returnBinding failsClient anddriverBothregistered,eitherorderMatchclientForexample,comparecompatiblestringsCall probePass theclientpointerBind clientProbereturnedzeroExit from step 3: NegativereturnBinding fails
A registered client and a registered driver meet at matching, then the core calls probe

A struct i2c_driver describes the driver that may bind to those clients. For a Device Tree driver, set .driver.name to the driver's name and .driver.of_match_table to the table of supported compatible strings. Assign the setup callback to .probe and, when explicit teardown is needed, the teardown callback to .remove. A driver can also supply .id_table, a table of struct i2c_device_id entries used for matching by I2C device name. A single driver object can serve multiple clients. Each probe call receives the client for that invocation.

In Linux 6.8, the probe callback takes one struct i2c_client * and returns int. A return of zero means the driver initialized that client and accepted the binding. A negative error code means setup did not succeed, and the client does not bind through that attempt. The remove callback also takes one struct i2c_client * and returns void. It runs when a bound client is detached. Its job is to stop any activity the driver started for that client and perform any explicit cleanup the driver needs. If probe fails, its error path must handle any cleanup it requires.

To register explicitly, define the struct i2c_driver with static storage duration. Include <linux/i2c.h> and have the module init function return i2c_add_driver(&sensor_driver) directly, where sensor_driver is your driver object. Returning the result propagates registration failure to the module loader. In the module exit function, call i2c_del_driver(&sensor_driver). Unregistering the driver detaches its bound clients and invokes their remove callbacks if supplied. If the module needs only these registration and unregistration steps, module_i2c_driver(sensor_driver) generates them for you.

On registration the driver core can match clients that already exist. Clients added later can match the same registered driver. A successful i2c_add_driver() means the driver joined the bus's driver list. The call can succeed even when no compatible client exists or when a matching client's probe fails. When tracing a device that does not work, ask separately whether Linux created the client, whether it matched the driver, and whether probe returned success. A matching compatible answers the software matching question. An address ACK answers a question about one transaction on the wires.

The next lesson, Talking to an I2C device, starts with the struct i2c_client * supplied to probe and asks how the driver uses it to exchange data with that device.

Key takeaways

  • SDA carries data and SCL carries the clock. Pull-ups bring released lines high.
  • A 7-bit address stays the same for reads and writes. The direction occupies a separate bit on the wire.
  • An i2c_client represents one device on one adapter. An i2c_driver supplies matching information and callbacks.
  • A successful i2c_add_driver() registers the driver. A successful probe binds it to a particular client.
Reflect
  1. Explain to a colleague, in two sentences: decode the address, direction and acknowledgment in a 7-bit I2C transaction.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close