Mbed OS (mbed 5) version of mbed 2 I2C_scanner app

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 // Original program found here: http://playground.arduino.cc/Main/I2cScanner
00002 // Modified by Domen Ornik, 4.5.2015
00003 
00004 #include "mbed.h"
00005 
00006 I2C i2c(I2C_SDA , I2C_SCL ); 
00007 
00008 int main() {
00009     printf("\nI2C Scanner");
00010     
00011     while(1) {
00012         int error, address;
00013         int nDevices;
00014       
00015         printf("Scanning...\n");
00016         
00017          nDevices = 0;
00018          
00019           for(address = 1; address < 127; address++ ) 
00020           {
00021             i2c.start();
00022             error = i2c.write(address << 1); //We shift it left because mbed takes in 8 bit addreses
00023             i2c.stop();
00024             if (error == 1)
00025             {
00026               printf("I2C device found at address 0x%X", address); //Returns 7-bit addres
00027               nDevices++;
00028             }
00029             else
00030             {
00031               //printf("I2C write returned error code 0x%X for address 0x%X\n", error, address);
00032             }
00033           }
00034           if (nDevices == 0)
00035             printf("No I2C devices found\n");
00036           else
00037             printf("\ndone\n");
00038         
00039           wait(5);           // wait 5 seconds for next scan
00040           
00041             }
00042         }
00043