Sub topic 14
Making an Arduino act as an I2C target
This chapter assumes you know the Wire library's controller calls (beginTransmission, endTransmission, requestFrom) and the transaction framing from earlier chapters: START, address byte, ACK/NACK, STOP. It also assumes you can wire two boards with pull-ups. Here you will turn an Arduino into a device that another Arduino reads and writes like a sensor.
When a target role is useful
An Arduino normally acts as the controller, which drives SCL and starts every transaction. It can also join the bus as a target and answer to its own address. Typical uses:
- Offloading timing-critical work (motor control, LED animation) to a second board and sending it commands over two wires.
- Exposing a sensor that has no I2C interface by wrapping it in a small board with a register map.
- Building a test double for a real I2C chip while you develop controller code.
A target never starts a transaction on its own. It cannot send data unless the controller asks for it. If the target needs attention, you need a separate interrupt line or the controller must poll.
How the roles map onto Wire calls
| Role | Joining the bus | Receiving data | Sending data |
|---|---|---|---|
| Controller | `Wire.begin()` | `Wire.requestFrom(addr, n)` then `Wire.read()` | `Wire.beginTransmission(addr)`, `Wire.write()`, `Wire.endTransmission()` |
| Target | `Wire.begin(addr)` | `Wire.onReceive(handler)`, then `Wire.read()` inside the handler | `Wire.onRequest(handler)`, then `Wire.write()` inside the handler |
The target does not poll the bus. The Wire library runs two callbacks that you register.
onReceiveruns after the controller finishes a write transaction (at its STOP or repeated START). It receives the number of bytes that arrived. The bytes wait in a receive buffer, and you drain them withWire.available()andWire.read().onRequestruns when the controller starts a read transaction addressed to you. Inside it you callWire.write()to load the bytes the controller will clock out.
The address passed to Wire.begin(addr) is a 7-bit address. Use 0x08 to 0x77. Addresses 0x00 to 0x07 and 0x78 to 0x7F are reserved for special purposes such as general call and 10-bit addressing.
A minimal target
This sketch stores the last byte it received and returns it on request.
#include <Wire.h>
volatile byte lastValue = 0;
void receiveEvent(int howMany) {
while (Wire.available()) {
lastValue = Wire.read();
}
}
void requestEvent() {
Wire.write(lastValue);
}
void setup() {
Wire.begin(8); // join the bus as a target at address 8
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
void loop() {
delay(100);
}The variable is volatile because the callbacks run in interrupt context, outside the normal flow of loop(). Without volatile, the compiler may cache the value in a register inside loop() and never see the update.
Wiring two boards
Connect the two boards as follows:
- Join GND to GND. Without a common reference, the signals mean nothing.
- Join SDA to SDA and SCL to SCL (A4 and A5 on an Uno, or the dedicated SDA and SCL pins).
- Provide one set of pull-ups for the whole bus. Many breakout boards already include them. Do not add a new pair per board without checking the combined resistance, since parallel pull-ups lower the total resistance.
- Do not connect the 5 V rails of two separately powered boards unless you intend to. If one board is 3.3 V and the other 5 V, use a level shifter as described in the earlier chapter.
A matching controller
This controller writes one byte, then reads one byte back from address 8.
#include <Wire.h>
const uint8_t TARGET_ADDRESS = 8;
void setup() {
Serial.begin(9600);
Wire.begin();
}
void loop() {
static uint8_t counter = 0;
counter++;
Wire.beginTransmission(TARGET_ADDRESS);
Wire.write(counter);
uint8_t error = Wire.endTransmission();
if (error != 0) {
Serial.print("Write failed, error ");
Serial.println(error);
delay(1000);
return;
}
if (Wire.requestFrom(TARGET_ADDRESS, (uint8_t)1) == 1) {
Serial.print("Sent ");
Serial.print(counter);
Serial.print(", read back ");
Serial.println(Wire.read());
} else {
Serial.println("No data returned");
}
delay(1000);
}Each line should show the same number sent and read back. If endTransmission returns 2, the address byte was not acknowledged: check wiring, grounds, and that the target sketch is running.
Building a register map
Real I2C devices follow a convention: the first byte of a write selects a register, and later reads return that register. You can make your Arduino behave the same way, so existing controller code such as the readRegister16 pattern works against it.
#include <Wire.h>
const uint8_t TARGET_ADDRESS = 8;
const uint8_t REG_COUNT = 4;
volatile uint8_t registers[REG_COUNT] = {0, 0, 0, 0};
volatile uint8_t selectedReg = 0;
void receiveEvent(int howMany) {
uint8_t reg = Wire.read(); // first byte is the register pointer
if (reg >= REG_COUNT) { // invalid pointer: discard the rest
while (Wire.available()) Wire.read();
return;
}
selectedReg = reg;
uint8_t index = reg;
while (Wire.available() && index < REG_COUNT) {
registers[index++] = Wire.read(); // extra bytes write consecutive registers
}
while (Wire.available()) Wire.read(); // drop anything beyond the map
}
void requestEvent() {
Wire.write(registers[selectedReg]);
}
void setup() {
Wire.begin(TARGET_ADDRESS);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
void loop() {
registers[0] = (uint8_t)(millis() / 1000); // register 0: uptime in seconds, low byte
delay(100);
}A controller sets the pointer with a write that contains only the register number, then reads with a repeated START:
#include <Wire.h>
void setup() {
Serial.begin(9600);
Wire.begin();
}
void loop() {
Wire.beginTransmission(8);
Wire.write(1); // select register 1
Wire.write(42); // and store 42 in it
Wire.endTransmission();
Wire.beginTransmission(8);
Wire.write(1); // pointer only, no data
Wire.endTransmission(false); // repeated START, keep the bus
if (Wire.requestFrom(8, 1) == 1) {
Serial.println(Wire.read()); // prints 42
}
delay(1000);
}Each register here is one byte, so every read in requestEvent is a single atomic access. A 16-bit value is different. If loop() is halfway through updating it when the controller reads, the controller gets half old and half new data. Disable interrupts briefly with noInterrupts() and interrupts() while writing multi-byte values, or copy them under that protection into a snapshot buffer.
Rules for the callbacks
The callbacks run from the I2C interrupt, and the controller is waiting during them. Follow these rules:
- Keep them short. Copy bytes, set a flag, return. Do the real work in
loop(). - Avoid
Serial.printinside them. Serial output can block when its buffer fills, and while it blocks, the bus stalls. Set a flag and print fromloop(). - Avoid
delay(). It depends on timer interrupts and is unreliable or blocking here. - Call
Wire.writeonly insideonRequest. Writing outside that callback on a target does not reach the controller at the right time. - Expect a 32-byte limit on AVR boards. The Wire buffers hold 32 bytes, so a single transaction cannot carry more.
What happens when things go wrong
- The controller asks for more bytes than you wrote. On AVR the target has nothing to send, and the controller usually reads 0xFF because SDA floats high. Always send as many bytes as the controller requests, or define a fixed message length.
- The target is busy. The AVR hardware holds SCL low (clock stretching) while a callback runs, so a slow handler slows the whole bus. A controller without clock-stretching support can then read garbage. Keep handlers fast.
- Two devices share an address. Giving your target address 0x68 on a bus that already has a real clock chip there causes collisions. Run the bus scanner first, and pick a free address.
- The target is reset or not yet booted. The controller sees a NACK on the address byte, and
endTransmissionreturns 2. Check this return value and retry rather than assuming success. - A 3.3 V board is the target of a 5 V controller. Pull-ups to 5 V can exceed the 3.3 V board's pin ratings. Pull the bus up to the lower voltage or add a level shifter.
Exercise
A target sketch prints every received byte with Serial.print inside onReceive. The controller occasionally reports a failed transaction at high traffic. Why, and what is the fix?
Show answer
Serial.print can block when its transmit buffer is full, and the callback runs in interrupt context while the controller waits on a stretched clock. The delay can cause timeouts or corrupted transfers. Fix it by copying the bytes into a volatile buffer and setting a flag in onReceive, then printing from loop() when the flag is set.
Exercise
In the register-map target, what does a controller read if it does a plain requestFrom(8, 1) right after the target boots and no write has happened?
Show answer
It reads registers[selectedReg]. Both start at zero, so it reads register 0, which holds the uptime in seconds (low byte) and is updated in loop().