Sub topic 15
Clock stretching
This chapter assumes you have read the earlier chapters on open-drain signaling, pull-up resistors and the structure of a transaction (START, address byte, ACK/NACK, STOP). You should also be comfortable with Wire.beginTransmission, Wire.endTransmission and Wire.requestFrom.
What clock stretching is
In I2C the controller normally generates the clock on SCL. Clock stretching lets a target slow that clock down. When a target needs more time, it holds SCL low after the controller has released it. The controller sees that the line has not risen and waits. When the target is ready, it releases SCL, the pull-up resistor raises the line, and the transaction continues.
This works because SCL is an open-drain line, like SDA. Any device can pull it low, and no device drives it high. The line is high only when every device has let go.
Targets stretch the clock for reasons like these:
- A sensor is still converting a measurement and cannot yet supply the next byte.
- A microcontroller acting as a target is running an interrupt handler and cannot yet load or read the data register.
- A device with a slow internal bus needs time to finish an earlier operation.
Where a target may stretch
The I2C specification lets a target stretch only while the controller has released SCL and the target holds it low. In practice this happens at the low phase of a clock pulse. Most devices stretch after the eighth bit and before the ACK bit, or between bytes.
A target cannot stretch SCL while the controller is holding it low. It can only extend a low period that is already in progress.
What the controller must do
A correct controller does not assume SCL went high just because it released the line. After releasing SCL, it reads the pin and waits until the pin is high before it counts that clock period as started. This is the whole mechanism. If a controller skips this check, it keeps clocking while the target is still holding the line low. The target then misses bits, and the data comes back wrong or shifted.
The hardware TWI peripheral on AVR-based Arduino boards (Uno, Nano, Mega) does this check in hardware. The Wire library on those boards therefore supports clock stretching without any extra code from you.
Support is not the same everywhere:
| Controller | Clock stretching behavior |
|---|---|
| AVR hardware TWI (Uno, Nano, Mega) | Waits for SCL to rise. Works with stretching targets. |
| Software (bit-banged) I2C | Depends on the library. Some do not check the SCL pin and fail with stretching targets. |
| Some other boards | Support varies by chip. Check the datasheet or core documentation, and look for a configurable stretch timeout. |
| Some single-board computers | Older hardware I2C controllers are known for mishandling stretching. Check your board's documentation. |
If a device works on one board and returns garbage on another, controller stretching support is a good first suspect.
The danger: waiting forever
If a target pulls SCL low and never lets go, the controller waits indefinitely. This can happen if a target crashes mid-transaction, loses power partway through, or is reset while holding the line. Your sketch then appears to hang inside endTransmission or requestFrom.
Newer versions of the Arduino AVR core add a timeout to Wire so a stuck bus cannot freeze the sketch permanently. The functions are:
Wire.setWireTimeout(timeout_us, reset_on_timeout)sets the timeout in microseconds. Ifreset_on_timeoutis true, the library resets the TWI hardware when the timeout happens.Wire.getWireTimeoutFlag()returns true if a timeout has occurred since the flag was last cleared.Wire.clearWireTimeoutFlag()clears that flag.
These functions exist only in newer cores, and the default timeout depends on the core version. The macro WIRE_HAS_TIMEOUT is defined when they are available, so you can guard the code with #ifdef. Not every board's Wire implementation provides them. Check the core you use.
When a transmission times out, endTransmission returns status code 5. The earlier error codes (1 to 4) are described in the Wire library chapter.
Example: reading with a timeout
This sketch sets a 25 ms timeout, reads a 16-bit register, and distinguishes a timeout from an ordinary NACK. Replace DEVICE_ADDRESS and REGISTER with values from your device's datasheet.
#include <Wire.h>
const uint8_t DEVICE_ADDRESS = 0x40; // change to your device's address
const uint8_t REGISTER = 0x00; // change to a register on your device
// Returns 0 on success, 1 for a bus timeout, 2 for any other failure.
uint8_t readRegister16(uint8_t address, uint8_t reg, uint16_t &value) {
Wire.beginTransmission(address);
Wire.write(reg);
uint8_t error = Wire.endTransmission(false); // repeated START
if (error == 5) return 1; // timeout
if (error != 0) return 2; // NACK or other error
if (Wire.requestFrom(address, (uint8_t)2) != 2) {
#ifdef WIRE_HAS_TIMEOUT
if (Wire.getWireTimeoutFlag()) return 1;
#endif
return 2;
}
value = (uint16_t)Wire.read() << 8;
value |= Wire.read();
return 0;
}
void setup() {
Serial.begin(9600);
Wire.begin();
#ifdef WIRE_HAS_TIMEOUT
Wire.setWireTimeout(25000, true); // 25 ms, reset TWI hardware on timeout
#endif
}
void loop() {
uint16_t value;
uint8_t result = readRegister16(DEVICE_ADDRESS, REGISTER, value);
if (result == 0) {
Serial.print("Value: 0x");
Serial.println(value, HEX);
} else if (result == 1) {
Serial.println("Bus timeout: a device may be holding SCL low");
#ifdef WIRE_HAS_TIMEOUT
Wire.clearWireTimeoutFlag();
#endif
} else {
Serial.println("Read failed (NACK or short read)");
}
delay(1000);
}With reset_on_timeout set to true, the library resets the TWI hardware after a timeout, so the next call starts from a clean state. The reset does not fix a target that still holds SCL low. If the target is stuck, the next transaction times out too.
Stretching in an Arduino target
An Arduino can also be the one that stretches. On AVR boards, the hardware TWI peripheral holds SCL low after a byte is received or requested until the software has dealt with it. Your onReceive and onRequest handlers run inside that window, so every microsecond spent in them is a microsecond of stretching.
A handler that calls delay, prints a long message over Serial, or reads a slow sensor can stretch the clock by milliseconds. A controller with a short timeout, or one that does not support stretching, will fail. The safer pattern is to keep handlers short:
- In
onReceive, copy the bytes into a variable and set a flag. - In
onRequest, send data that is already prepared. - Do the slow work in
loop, and publish the result when it is done.
This is also why the target example earlier in the tutorial uses volatile for lastValue and keeps the handlers tiny.
Hardware that breaks stretching
Because stretching depends on a target being able to pull SCL low and the controller being able to see it, some parts of a bus can break it:
- Unidirectional level shifters. A shifter that passes SCL only from controller to target cannot carry the target's pull-down back. Use a bidirectional shifter on both lines (see the level shifting chapter).
- Push-pull drivers. If a controller actively drives SCL high instead of releasing it, it fights the target and may damage the output stage. Standard Wire on Arduino uses open-drain behavior, so this mainly affects custom or software drivers.
- Weak pull-ups or large capacitance. The rising edge after a release can be slow. A controller waiting for SCL to rise cannot tell a slow edge from a stretch, so total delay grows. Slow edges also push the bus out of timing limits at higher speeds.
- Multiplexers. The TCA9548A passes SCL bidirectionally, so stretching works through it. A multiplexer chosen without checking this may not.
Choosing a design
| Situation | Suggested approach |
|---|---|
| Target needs a long time to prepare data | Prefer a device that stretches, or poll a status register and read when ready. |
| Target is an Arduino | Keep `onReceive` and `onRequest` short and defer slow work to `loop`. |
| Controller is software I2C | Confirm the library checks SCL after releasing it. |
| Bus must never hang | Set a Wire timeout, and handle error code 5. |
| Intermittent garbage on a board that works elsewhere | Check controller stretching support before suspecting wiring. |
Exercise
A sketch hangs inside requestFrom whenever a certain sensor is busy converting. The sensor uses clock stretching. Name two changes that stop the sketch from freezing, and say what endTransmission returns when a timeout occurs.
Show answer
Enable a Wire timeout with Wire.setWireTimeout(timeoutus, true), guarded by #ifdef WIREHAS_TIMEOUT, and handle the failure when it triggers. Alternatively, avoid reading until the device is ready, for example by polling a status register or waiting for the documented conversion time. endTransmission returns 5 when a timeout occurs.
Exercise
An Arduino target's onRequest handler calls delay(50) before Wire.write. A controller with a 25 ms timeout reports failures. Explain why, and how to fix it.
Show answer
The AVR hardware holds SCL low (stretches the clock) while the handler runs, so the 50 ms delay stretches the clock past the controller's 25 ms timeout. Fix it by removing the delay from the handler. Prepare the data in loop, store it in a volatile variable, and have onRequest only call Wire.write with the stored value.