Skip to content

Explanation of the functions of the Wire library

Koepel edited this page Jul 16, 2019 · 25 revisions

Wire.begin()

The Wire.begin() starts the hardware and software.

What about a delay after a Wire.begin() ?
A delay after Wire.begin() is probaby not needed. There are often external pullup resistors that keep the SDA and SCL signals high. Even without external pullup resistors there is probably no delay needed. I have not heard of a sensor yet, that could not capture the first START condition after floating bus signals.

Wire.beginTransmission(), Wire.write(), Wire.endTransmission()

These three functions work together.
The Wire.beginTransmission() and Wire.endTransmission() should never be used on their own.
To test if a sensor will acknowledge to its address, a Wire.write() in the middle is not needed.
The maximum number of bytes that can be written depends on the buffer size (inside the Wire library).
Read more about the buffer size: Buffer size of the Wire library.

Wire.requestFrom()

This function reads data from a sensor. After it is finished, the received data is in a buffer (inside the Wire library). That data can be read with Wire.read(). The Wire.available() tells how many bytes are still in that buffer.

When there was a problem during the I2C bus activity, the received bytes up to that point are not reliable. With the Arduino Wire library it is not even possible to know if there are any reliable bytes before the bus error did happen. It is therefor better to first check for errors and if there are no errors, then read all the bytes.
Checking for errors might not be needed, see the Check for bus errors ? page.