I2c bus scanning

Is there a simple way to scan the I2C bus and poll for any device response ? In theory I know it’s possible to detect as I do this all the time on bare metal LPC devices, just not sure the imp API or the STM supports it.

Already found a way. This little piece of code does the trick and seems to work on all I2C devices I tested in the meantime

i2c <- null;
Address <- 0;

function initHardware()
	i2c <- hardware.i2c0; // imp005

function findDevice() 
    local e = i2c.write(Address,"\x00"); //Try write some data
    if (e == 0 )// NO_ERROR => Found something.
		server.log(format("Found device @ address 0x%02x", Address>>1));

    Address+=2; //Increment by 2.
    if (Address < 254)
	    imp.wakeup(0.1, findDevice.bindenv(this));
	    server.log("Finished scanning");


This alternative is from the Knowledgebase and is more compact:

i2c <- hardware.i2c89;   // Set to desired I2C bus

for (local i = 2 ; i < 256 ; i+=2) {
    if (i2c.read(i, "", 1) != null) server.log(format("Device at address: 0x%02X", i));

It’s also best not to write arbitrary things to devices if at all possible :slight_smile: