Sub topic 7
Using the Wire library
The Wire library is the Arduino API for I2C. This chapter covers how its calls map to bus transactions, how to write and read data, what the return codes mean, and which mistakes cause most failures.
This chapter assumes you know the following:
- Basic sketch structure (
setupandloop) and the Serial Monitor. - The I2C basics from earlier chapters: SDA and SCL, pull-up resistors, 7-bit addresses, and START, ACK/NACK and STOP.
- Hexadecimal numbers.
The working model
Wire hides the bus timing, but it does not hide the transaction structure. Two ideas explain most of its behavior.
- Writes are buffered.
beginTransmission(),write()andendTransmission()do not send bytes one at a time as you call them.beginTransmission()andwrite()fill an internal buffer in RAM. Nothing goes onto the wire untilendTransmission()is called. That call sends START, the address byte, the buffered bytes and then STOP (or no STOP, if you ask for that). - Reads are blocking.
requestFrom()sends START and the address with the read bit set, clocks in the number of bytes you asked for, and returns. The bytes then wait in a receive buffer until you fetch them withread().
The buffer size is 32 bytes on AVR boards such as the Uno. Other cores may differ. A single transaction on an AVR board therefore cannot carry more than 32 bytes, and one of those bytes is used if you write a register pointer first.
Starting Wire
Call Wire.begin() once, normally in setup(). With no argument, the board joins the bus as the controller. With an address, as in Wire.begin(8), it joins as a target. Targets are covered in a later chapter.
Wire.begin() configures the hardware I2C pins and enables the internal pull-ups on many AVR boards. Those internal pull-ups are weak (around 20 to 50 kΩ), so you should still use external pull-ups on any bus that has more than a short wire and one device.
On boards with more than one I2C port, such as Wire1 on many ARM-based boards, the same API exists on each object. Replace Wire with Wire1 in every call.
Writing to a device
A write is three steps: begin, queue bytes, end.
#include <Wire.h>
const uint8_t DEVICE = 0x40;
void setup() {
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(DEVICE); // address only, no bus activity yet
Wire.write(0x01); // register pointer
Wire.write(0xA5); // value to store
byte error = Wire.endTransmission(); // sends START ... STOP
Serial.print("endTransmission returned ");
Serial.println(error);
}
void loop() {
}write() accepts a single byte, a string, or a buffer and a length. It returns the number of bytes queued. If the buffer is full, it returns less than you asked for, and the extra bytes are lost.
Most register-based devices expect the first byte after the address to be the register number. Every byte after it goes to that register, and many devices then increment the register number automatically for each further byte. Check the datasheet for this "auto-increment" behavior. Without it, a multi-byte write would overwrite the same register repeatedly.
Return codes of endTransmission
endTransmission() returns a status code. Always check it. It is the only feedback you get about whether a write worked.
| Code | Meaning | Usual cause |
|---|---|---|
| 0 | Success | The device ACKed the address and every data byte. |
| 1 | Data too long for the buffer | More bytes were queued than the buffer holds. |
| 2 | NACK on address | Wrong address, device unpowered, or wiring fault. |
| 3 | NACK on data | The device refused a byte, for example an invalid register. |
| 4 | Other error | Often a bus fault, such as SDA or SCL held low. |
| 5 | Timeout | Reported by some newer cores when the bus hangs. |
Codes 4 and 5 vary between cores. If you see them, check wiring and the pull-ups before looking at your code.
Reading from a device
requestFrom(address, quantity) returns the number of bytes actually received. Compare that value to what you asked for. Do not assume the read worked.
#include <Wire.h>
const uint8_t DEVICE = 0x40;
void setup() {
Serial.begin(9600);
Wire.begin();
uint8_t got = Wire.requestFrom(DEVICE, (uint8_t)2);
if (got != 2) {
Serial.println("Read failed");
return;
}
while (Wire.available()) {
Serial.println(Wire.read(), HEX);
}
}
void loop() {
}The cast (uint8_t)2 matters on some cores. requestFrom is overloaded, and passing a plain int for the quantity can pick a different overload than the one you intended.
available() returns how many received bytes remain unread. read() returns the next one, or -1 if none is left. Reading more bytes than requestFrom returned gives you -1 (0xFFFF when stored in a uint16_t), which looks like real data. Using available() as the loop condition prevents this.
Reading a register: the repeated START
Most devices need to know which register to read before they send it. This requires a write of the register number, followed by a read, without a STOP in between. The earlier readRegister16 example does exactly that.
#include <Wire.h>
bool readRegister8(uint8_t address, uint8_t reg, uint8_t &value) {
Wire.beginTransmission(address);
Wire.write(reg);
if (Wire.endTransmission(false) != 0) { // false: no STOP, send repeated START next
return false;
}
if (Wire.requestFrom(address, (uint8_t)1) != 1) {
return false;
}
value = Wire.read();
return true;
}
void setup() {
Serial.begin(9600);
Wire.begin();
uint8_t id;
if (readRegister8(0x68, 0x75, id)) {
Serial.print("WHO_AM_I = 0x");
Serial.println(id, HEX);
} else {
Serial.println("Read failed");
}
}
void loop() {
}The argument to endTransmission(false) controls the STOP. With true (the default), Wire sends STOP and releases the bus. With false, it holds the bus and the following requestFrom begins with a repeated START. Some devices work with a STOP followed by a fresh START, and some do not. The repeated START is the safe choice. It is also the only correct choice on a bus with more than one controller, because it prevents another controller from taking the bus between the two halves.
A related detail is the third argument of requestFrom(address, quantity, stop). It lets you leave the bus held after a read, which is occasionally needed for chained transactions. The default of true is right in nearly all cases.
Wire function summary
| Function | Purpose | Returns |
|---|---|---|
| `begin()` | Join the bus as controller | nothing |
| `begin(addr)` | Join the bus as target | nothing |
| `beginTransmission(addr)` | Start queuing a write | nothing |
| `write(x)` | Queue a byte, string or buffer | bytes queued |
| `endTransmission([stop])` | Send the queued data | status code |
| `requestFrom(addr, n[, stop])` | Read n bytes | bytes received |
| `available()` | Count unread received bytes | count |
| `read()` | Take the next received byte | byte, or -1 |
| `setClock(hz)` | Set the bus frequency | nothing |
Common errors
- Passing the 8-bit address. Some datasheets and breakout silkscreens quote an 8-bit write address such as 0xD0. Wire expects the 7-bit address, here 0x68. Shift right by one.
- Not checking return values. A failed
endTransmissionor shortrequestFromis silent unless you test for it. The sketch then prints stale or garbage data. - Exceeding the buffer. Writing more than 32 bytes in one transmission fails on AVR. Split large transfers into several transmissions, remembering that the device may need the register pointer repeated.
- Mixing up byte order. Many sensors send the high byte first. Combine with
(high << 8) | low, and cast toint16_tfor signed values. - Calling Wire from an interrupt handler. Wire uses interrupts internally and is not safe to call from your own ISR. Set a flag in the ISR and do the bus work in
loop(). - Forgetting
begin(). Without it, calls return errors or hang.
Bus speed from the sketch
Wire.setClock(400000) requests 400 kHz Fast mode. Call it after Wire.begin(). The setting applies to the whole bus, so the slowest device and your pull-up resistors decide the highest safe value. If a device that worked at the default 100 kHz starts to fail, lower the clock before searching for other causes.
Exercise
A sketch calls Wire.beginTransmission(0x68), Wire.write(0x75), Wire.endTransmission(), and then Wire.requestFrom(0x68, 1). The device sometimes returns 0xFF instead of its ID. What change should you try first, and why?
Show answer
Change endTransmission() to endTransmission(false) so the requestFrom begins with a repeated START instead of STOP followed by START. Some devices lose their register pointer or release the bus state when a STOP arrives. Also check that requestFrom returned 1 before calling read(), because 0xFF may be the -1 that read() gives when no byte was received.
Exercise
endTransmission() returns 2 when you write to address 0x3C, but the same code works for 0x3D on another board. List two likely causes.
Show answer
The address is probably wrong or the device is not responding. Examples are an address pin or jumper set differently so the device is really at 0x3D, or the device is unpowered or wired incorrectly (SDA and SCL swapped, no common ground). Code 2 means nothing ACKed the address, so running an address scanner is the quickest way to see where the device actually answers.