Skip to content

Explanation of the functions of the Wire library

Koepel edited this page Feb 9, 2021 · 24 revisions

Initialize: 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.

Function Parameters Return value notes
Wire.begin() 1. The own I2C Slave address. - The parameter is only used when the Arduino is set in Slave mode. Some boards also set the pins for SDA and SCL.

Write data: 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.

Function Parameters Return value notes
Wire.beginTransmission() 1. The I2C address. - -
Wire.write() 1. A byte or a zero-terminated string or a pointer.
2. The number of bytes when the first parameter is a pointer.
- The return value tells if the data fits in the buffer. That is not used. If the buffer size is unknown, then Wire.availableForWrite() tells how large the buffer is.
Wire.endTransmission() 1. false for a repeated start. An error code, 0 is no error. The parameter is for the STOP condition. When there is no STOP, then the next START will be a repeated start.

Read data: 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.

Function Parameters Return value notes
Wire.requestFrom() 1. The I2C address
2. The number of requested bytes.
The number of received bytes. There is a third parameter, but that is not used in a single-Master bus.
Wire.available() - The number of bytes that are still in a buffer. -
Wire.read() - 8-bit data as part of a integer. The integer makes it possible to return -1 when there was no data