[2014-May-9: updated to work with Arduino 1.0 and moved into github]
One of the challenges of working with I2C (aka “two-wire” or “TWI” or “Wire”) devices is knowing the I2C address of the device. Older devices have a fixed address, or a “choose one-of-four” approach. But newer I2C devices have fully programmable addresses, leading to cases of not knowing what address a device is at.
Fortunately, there’s a technique one can use to “scan” an I2C bus and determine these addresses. Conceptually it’s very similar to a network “ping”. Below is an Arduino sketch “I2CScanner.pde” that turns an Arduino into an I2C bus scanner.
– I2CScanner.ino — Turn Arduino into I2C bus scanner (github repo)
When loaded up on an Arduino, the sketch will immediately scan the I2C network, showing which addresses are responding.
For example, the above output is from an I2C bus with four slave devices on it (one BlinkM MaxM, three regular BlinkMs).
(Notice the 2 pull-up resistors on SDA & SCL. This is needed for longer bus lengths)
One thing to notice about the I2CScanner output is that although there are four devices on the bus, only three addresses were detected. This is because unlike IP networks and “ping”, you can’t tell if two devices have the same address. They’ll both respond to commands sent to them just fine, you just can’t read back data from them.
How it works
In I2C, the first byte transmitted/written by the master to a slave is the address of the slave. If there is a slave at that address, the slave will signal the I2C bus, otherwise it leaves it alone. We can use this to implement a bus scanner.
The Arduino “Wire” library utilizes a set of C functions called “twi.c”. One of those functions is “twi_writeTo()”. This function is used to both send the address of the slave down the bus and also to write data to slaves. It returns 0 if it was able to successfully transmit a byte or non-zero if it couldn’t. Since the very first write to a slave is its address, a very simple bus scanner using it would be:
void scanI2CBus(byte from_addr, byte to_addr) {
byte data = 0; // not used, just a ptr to feed to twi_writeTo()
for( byte addr = from_addr; addr < = to_addr; addr++ ) {
byte rc = twi_writeTo(addr, &data, 0, 1, 0);
if( rc == 0 ) {
Serial.printl("device found at address ");
Serial.println(addr,DEC);
}
}
}
In the I2CScanner sketch, this function is extended a bit to support a callback function. The callback function is called with the result of every address scan. In I2CScanner, this callback function is called “scanFunc()” and just prints out “found!” or nothing, but it could be modified to do more complex tasks like doing additional I2C transactions to figure out what kind of device it is, or setting all the devices to a known state, etc.