Wire
#include <Wire.h>
Description
This library allows you to communicate with I2C/TWI devices. On the Arduino
boards with the R3 layout (1.0 pinout), the SDA (data line) and SCL (clock line)
are on the pin headers close to the AREF pin. The Arduino Due has two I2C/TWI
interfaces SDA1 and SCL1 are near to the AREF pin and the additional one is on
pins 20 and 21.
As a reference the table below shows where TWI pins are located on various
Arduino boards.
|
|
Board: | I2C/TWI pins
|
Nano | A4 (SDA), A5 (SCL)
|
UNO, Ethernet | A4 (SDA), A5 (SCL)
|
Mega2560 | 20 (SDA), 21 (SCL)
|
Leonardo | 20 (SDA), 21 (SCL), SDA1, SCL1
|
As of Arduino 1.0, the library inherits from the Stream functions, making it
consistent with other read/write libraries. Because of this, send() and
receive() have been replaced with read() and write().
Recent versions of the Wire library can use timeouts to prevent a lockup in the
face of certain problems on the bus, but this is not enabled by default (yet)
in current versions. It is recommended to always enable these timeouts when
using the Wire library. See the Wire.setWireTimeout function for more details.
Note: There are both 7 and 8-bit versions of I2C addresses. 7 bits identify the
device, and the eighth bit determines if it’s being written to or read from.
The Wire library uses 7 bit addresses throughout. If you have a datasheet or
sample code that uses 8-bit address, you’ll want to drop the low bit (i.e. shift
the value one bit to the right), yielding an address between 0 and 127. However
the addresses from 0 to 7 are not used because are reserved so the first address
that can be used is 8. Please note that a pull-up resistor is needed when
connecting SDA/SCL pins. Please refer to the examples for more information.
MEGA 2560 board has pull-up resistors on pins 20 and 21 onboard.
The Wire library implementation uses a 32 byte buffer, therefore any communication
should be within this limit. Exceeding bytes in a single transmission will just
be dropped.
To use this library:
#include <Wire.h>
/*F********************************************************************
*
**********************************************************************/
begin()
Description
This function initializes the Wire library and join the I2C bus as a
controller or a peripheral. This function should normally be called only once.
Syntax
Wire.begin()
Wire.begin( address
)
Parameters
address:
the 7-bit slave address (optional); if not specified, join the bus
as a controller device.
Returns
None.
/*F********************************************************************
*
**********************************************************************/
end()
Description
Disable the Wire library, reversing the effect of Wire.begin(). To use the
Wire library again after this, call Wire.begin() again.
Note: This function was not available in the original version of the Wire
library and might still not be available on all platforms. Code that needs
to be portable across platforms and versions can use the WIRE_HAS_END macro,
which is only defined when Wire.end() is available.
Syntax
Wire.end()
Parameters
None.
Returns
None.
/*F********************************************************************
*
**********************************************************************/
requestFrom()
Description
This function is used by the controller device to request bytes from a
peripheral device. The bytes may then be retrieved with the available()
and read() functions. As of Arduino 1.0.1, requestFrom() accepts a
boolean argument changing its behavior for compatibility with certain I2C
devices. If true, requestFrom() sends a stop message after the request,
releasing the I2C bus. If false, requestFrom() sends a restart message
after the request. The bus will not be released, which prevents another
master device from requesting between messages. This allows one master
device to send multiple requests while in control. The default value is
true.
Syntax
Wire.requestFrom( address
, quantity
)
Wire.requestFrom( address
, quantity
, stop
)
Parameters
address:
the 7-bit slave address of the device to request bytes from.
quantity:
the number of bytes to request.
stop:
true or false. true will send a stop message after the request,
releasing the bus. False will continually send a restart after the request,
keeping the connection active.
Returns
byte : the number of bytes returned from the peripheral device
/*F********************************************************************
*
**********************************************************************/
beginTransmission()
Description
This function begins a transmission to the I2C peripheral device with the
given address. Subsequently, queue bytes for transmission with the write()
function and transmit them by calling endTransmission().
Syntax
Wire.beginTransmission( address
)
Parameters
address:
the 7-bit address of the device to transmit to.
Returns
None.
/*F********************************************************************
*
**********************************************************************/
endTransmission()
Description
This function ends a transmission to a peripheral device that was begun by
beginTransmission() and transmits the bytes that were queued by write(). As
of Arduino 1.0.1, endTransmission() accepts a boolean argument changing its
behavior for compatibility with certain I2C devices. If true, endTransmission()
sends a stop message after transmission, releasing the I2C bus. If false,
endTransmission() sends a restart message after transmission. The bus will
not be released, which prevents another controller device from transmitting
between messages. This allows one controller device to send multiple
transmissions while in control. The default value is true.
Syntax
Wire.endTransmission()
Wire.endTransmission( stop
)
Parameters
stop:
true or false. True will send a stop message, releasing the bus after
transmission. False will send a restart, keeping the connection active.
Returns
0: success.
1: data too long to fit in transmit buffer.
2: received NACK on transmit of address.
3: received NACK on transmit of data.
4: other error.
5: timeout
/*F********************************************************************
*
**********************************************************************/
write()
Description
This function writes data from a peripheral device in response to a request
from a controller device, or queues bytes for transmission from a controller
to peripheral device (in-between calls to beginTransmission() and
endTransmission()).
Syntax
Wire.write( value
)
Wire.write( string
)
Wire.write( data
, length
)
Parameters
value:
a value to send as a single byte.
string:
a string to send as a series of bytes.
data:
an array of data to send as bytes.
length:
the number of bytes to transmit.
Returns
The number of bytes written (reading this number is optional).
Example
/*H********************************************************************
*
**********************************************************************/
#include <Wire.h>
byte val = 0;
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Wire.begin(); // Join I2C bus
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{
Wire.beginTransmission( 44 ); // TRANSMIT TO DEVICE NUMBER 44 (0x2C)
Wire.write( val ); // SENDS VALUE BYTE
Wire.endTransmission(); // STOP TRANSMITTING
val++; // INCREMENT VALUE
if(val == 64)
val = 0; // REACHED 64TH POSITION (MAX), START OVER FROM LOWEST VALUE
delay( 500 );
}
/*F********************************************************************
*
**********************************************************************/
available()
Description
This function returns the number of bytes available for retrieval with read().
This function should be called on a controller device after a call to
requestFrom() or on a peripheral inside the onReceive() handler. available()
inherits from the Stream utility class.
Syntax
Wire.available()
Parameters
None.
Returns
The number of bytes available for reading.
/*F********************************************************************
*
**********************************************************************/
read()
Description
Reads a byte that was transmitted from a peripheral device to a controller
device after a call to requestFrom() or was transmitted from a controller
device to a peripheral device. read() inherits from the Stream utility class
Syntax
Wire.read()
Parameters
None.
Returns
The next byte received.
/*F********************************************************************
* Example
**********************************************************************/
#include <Wire.h>
#define BAUD 9600
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Wire.begin(); // JOIN I2C BUS (ADDRESS OPTIONAL FOR CONTROLLER DEVICE)
Serial.begin( BAUD ); // START SERIAL FOR OUTPUT
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{
Wire.requestFrom( 2, 6 );// REQUEST 6 BYTES FROM SLAVE DEVICE NUMBER TWO
while( Wire.available() ) // SLAVE MAY SEND LESS THAN REQUESTED
{
char c = Wire.read(); // RECEIVE A BYTE AS CHARACTER
Serial.print( c ); // PRINT CHARACTER
}
delay( 500 );
}
/*F********************************************************************
*
**********************************************************************/
setClock()
Description
This function modifies the clock frequency for I2C communication. I2C peripheral
devices have no minimum working clock frequency, however 100KHz is usually the
baseline.
Syntax
Wire.setClock( clockFrequency
)
Parameters
clockFrequency: the value (in Hertz) of the desired communication clock. Accepted
values are 100000 (standard mode) and 400000 (fast mode). Some processors also
support 10000 (low speed mode), 1000000 (fast mode plus) and 3400000 (high
speed mode). Please refer to the specific processor documentation to make
sure the desired mode is supported.
Returns
None.
/*F********************************************************************
*
**********************************************************************/
onReceive()
Description
Registers a function to be called when a peripheral device receives a transmission
from a controller device.
Syntax
Wire.onReceive( handler
)
Parameters
handler:
the function to be called when the peripheral device receives
data; this should take a single int parameter (the number of bytes read
from the controller device) and return nothing.
Returns
None.
/*F********************************************************************
*
**********************************************************************/
onRequest()
Description
This function registers a function to be called when a controller device
requests data from a peripheral device.
Syntax
Wire.onRequest( handler
)
Parameters
handler:
the function to be called, takes no parameters and returns nothing.
Returns
None.
/*F********************************************************************
*
**********************************************************************/
setWireTimeout()
Description
Sets timeout for Wire transmissions in master mode.
Note: these timeouts are almost always an indication of an underlying problem, such as misbehaving devices, noise, insufficient shielding, or other electrical problems. These timeouts will prevent your sketch from locking up, but not solve these problems. In such situations there will often (also) be data corruption which doesn’t result in a timeout or other error and remains undetected. So when a timeout happens, it is likely that some data previously read or written is also corrupted. Additional measures might be needed to more reliably detect such issues (e.g. checksums or reading back written values) and recover from them (e.g. full system reset). This timeout and such additional measures should be seen as a last line of defence, when possible the underlying cause should be fixed instead.
Syntax
Wire.setWireTimeout( timeout
, reset_on_timeout
)
Wire.setWireTimeout()
Parameters
timeout:
a timeout in microseconds, if zero then timeout checking is
disabled
reset_on_timeout:
if true then Wire hardware will be automatically reset on
timeout
When this function is called without parameters, a default timeout is configured that should be sufficient to prevent lockups in a typical single-master configuration.
Returns
None.
/*F********************************************************************
* Example Code
**********************************************************************/
#include <Wire.h>
byte x = 0;
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Wire.begin(); // join i2c bus (address optional for master)
#if defined( WIRE_HAS_TIMEOUT )
Wire.setWireTimeout( 3000 /* us */, true /* reset_on_timeout */);
#endif
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{
/* First, send a command to the other device */
Wire.beginTransmission( 8 ); // TRANSMIT TO DEVICE #8
Wire.write( 123 ); // SEND COMMAND
byte error = Wire.endTransmission(); // RUN TRANSACTION
if( error )
{
Serial.println( "Error occured when writing");
if(error == 5)
Serial.println( "It was a timeout" );
}
delay( 100 );
// THEN, READ RESULT
#if defined( WIRE_HAS_TIMEOUT )
Wire.clearWireTimeoutFlag();
#endif
byte len = Wire.requestFrom( 8, 1 ); // REQUEST 1 BYTE FROM DEVICE #8
if( len == 0 )
{
Serial.println("Error occured when reading");
#if defined(WIRE_HAS_TIMEOUT)
if( Wire.getWireTimeoutFlag() )
Serial.println( "It was a timeout" );
#endif
}
delay( 100 );
}
Notes and Warnings
How this timeout is implemented might vary between different platforms, but
typically a timeout condition is triggered when waiting for (some part of)
the transaction to complete (e.g. waiting for the bus to become available
again, waiting for an ACK bit, or maybe waiting for the entire transaction
to be completed).
When such a timeout condition occurs, the transaction is aborted and
endTransmission() or requestFrom() will return an error code or zero bytes
respectively. While this will not resolve the bus problem by itself (i.e.
it does not remove a short-circuit), it will at least prevent blocking
potentially indefinitely and allow your software to detect and maybe solve
this condition.
If reset_on_timeout was set to true and the platform supports this, the Wire
hardware is also reset, which can help to clear any incorrect state inside
the Wire hardware module. For example, on the AVR platform, this can be
required to restart communications after a noise-induced timeout.
When a timeout is triggered, a flag is set that can be queried with
getWireTimeoutFlag() and must be cleared manually using clearWireTimeoutFlag()
(and is also cleared when setWireTimeout() is called).
Note that this timeout can also trigger while waiting for clock stretching
or waiting for a second master to complete its transaction. So make sure to
adapt the timeout to accomodate for those cases if needed. A typical timeout
would be 25ms (which is the maximum clock stretching allowed by the SMBus
protocol), but (much) shorter values will usually also work.
Portability Notes
This function was not available in the original version of the Wire library
and might still not be available on all platforms. Code that needs to be
portable across platforms and versions can use the WIRE_HAS_TIMEOUT macro,
which is only defined when Wire.setWireTimeout(), Wire.getWireTimeoutFlag()
and Wire.clearWireTimeout() are all available.
When this timeout feature was introduced on the AVR platform, it was initially
kept disabled by default for compatibility, expecting it to become enabled
at a later point. This means the default value of the timeout can vary between
(versions of) platforms. The default timeout settings are available from the
WIRE_DEFAULT_TIMEOUT and WIRE_DEFAULT_RESET_WITH_TIMEOUT macro.
If you require the timeout to be disabled, it is recommended you disable it
by default using setWireTimeout(0), even though that is currently the default.
/*F********************************************************************
*
**********************************************************************/
clearWireTimeoutFlag()
Description
Clears the timeout flag.
Timeouts might not be enabled by default. See the documentation for
Wire.setWireTimeout() for more information on how to configure timeouts and
how they work.
Syntax
Wire.clearTimeout()
Parameters
None.
Returns
bool: The current value of the flag
Portability Notes
This function was not available in the original version of the Wire library
and might still not be available on all platforms. Code that needs to be
portable across platforms and versions can use the WIRE_HAS_TIMEOUT macro,
which is only defined when Wire.setWireTimeout(), Wire.getWireTimeoutFlag()
and Wire.clearWireTimeout() are all available.
/*F********************************************************************
*
**********************************************************************/
getWireTimeoutFlag()
Description
Checks whether a timeout has occured since last time flag was cleared.
This flag is set is set whenever a timeout occurs and cleared when
Wire.clearWireTimeoutFlag() is called, or when the timeout is changed using
Wire.setWireTimeout().
Syntax
Wire.getWireTimeoutFlag()
Parameters
None.
Returns
bool: current value of the flag
Portability Notes
This function was not available in the original version of the Wire library
and might still not be available on all platforms. Code that needs to be
portable across platforms and versions can use the WIRE_HAS_TIMEOUT macro,
which is only defined when Wire.setWireTimeout(), Wire.getWireTimeoutFlag()
and Wire.clearWireTimeout() are all available.