This code provides capabilities to find the address of connected I2C devices

Dependencies:   mbed

main.cpp

Committer:
Makodan
Date:
2018-05-03
Revision:
1:6a79412e380e
Parent:
0:1301fb16e306

File content as of revision 1:6a79412e380e:

// Original program found here: http://playground.arduino.cc/Main/I2cScanner
// Modified by Domen Ornik, 4.5.2015
#include "mbed.h"

I2C i2c(PB_7, PB_6); 
Serial pc(USBTX, USBRX);

int main() {
    pc.baud(115200);
    pc.printf("\nI2C Scanner");
    
    while(1) {
        int error, address;
        int nDevices;
      
        pc.printf("Scanning...\n");
        
         nDevices = 0;
         
          for(address = 1; address < 127; address++ ) 
          {
            i2c.start();
            error = i2c.write(address << 1); //We shift it left because mbed takes in 8 bit addreses
            i2c.stop();
            if (error == 1)
            {
              pc.printf("I2C device found at address 0x%X", address); //Returns 7-bit addres
              nDevices++;
            }

          }
          if (nDevices == 0)
            pc.printf("No I2C devices found\n");
          else
            pc.printf("\ndone\n");
        
          wait(2);           // wait 5 seconds for next scan
          
            }
        }