2
\$\begingroup\$

I am trying to understand a C function from a legacy project which is supposed to manage the clock line for an I2C interface. It basically does as follow:

  • Set pin to output: P0_1 |= 0b00000010; and then drives it low: P0_1 = 0;.
  • Or set as input: P0_1 &= 0b11111101; and wait for the clock line to be high: while (!P0_1) { wait(1); }.

What I don't understand is the second case, code comment says:

Set as input with pull-up to wait for the slave to be ready before driving the clock line to high.

How does this work? Is this how the master slows down its clock rate to let the slave follows it?

\$\endgroup\$
2
  • \$\begingroup\$ Do you know how I2C works (not the code but the actual protocol)? If not, you should read the specification. \$\endgroup\$ – Eugene Sh. Oct 26 '20 at 15:46
  • \$\begingroup\$ I am working on it! I just don't understand this implementation, other examples on the internet simply uses a delay for the slave to capture the falling or rising of the SCL... \$\endgroup\$ – Cinn Oct 26 '20 at 15:55
7
\$\begingroup\$

This is related to a feature of the IIC protocol called clock stretching. If a peripheral device is unable to process data from the bus master in time (or prepare its output to be transmitted back to the master), it will continue hold the SCL line low (remember that it is open-drain, so there is no bus contention), until it is ready for transmission to continue. Once it releases the clock to indicate that it is ready for the next cycle, the master can then continue clocking the bus.

An IIC-protocol-compliant master is required to support clock stretching after the ACK bit (in high-speed mode) and at all rising edge clock transitions (in low-speed mode). If it uses a delay to blindly clock the bus, it may transmit/issue edges before the peripheral is ready, causing communication failures. Famously, the Raspberry Pi had a defect in its drivers/firmware such that it did not wait for peripherals that were stretching the clock -- a delay-only realization of an I2C master would suffer from this exact defect unless it were only used with peripherals guaranteed not to stretch the clock.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.