Advertisement
ScienceGeyser

I2C Scanner ARM M0

May 14th, 2022
1,227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // --------------------------------------
  2. // i2c_scanner
  3. //
  4. // Modified from https://playground.arduino.cc/Main/I2cScanner/
  5. // Modified for ARM M0 Native USB
  6. // --------------------------------------
  7.  
  8. #include <Wire.h>
  9.  
  10. // Set I2C bus to use: Wire, Wire1, etc.
  11. #define WIRE Wire
  12.  
  13. void setup() {
  14.   WIRE.begin();
  15.  
  16.   SerialUSB.begin(115200);
  17.   while (!SerialUSB)
  18.      delay(100);
  19.   SerialUSB.println("\nI2C Scanner");
  20. }
  21.  
  22.  
  23. void loop() {
  24.   byte error, address;
  25.   int nDevices;
  26.  
  27.   SerialUSB.println("Scanning...");
  28.  
  29.   nDevices = 0;
  30.   for(address = 1; address < 127; address++ )
  31.   {
  32.     // The i2c_scanner uses the return value of
  33.     // the Write.endTransmisstion to see if
  34.     // a device did acknowledge to the address.
  35.     WIRE.beginTransmission(address);
  36.     error = WIRE.endTransmission();
  37.  
  38.     if (error == 0)
  39.     {
  40.       SerialUSB.print("I2C device found at address 0x");
  41.       if (address<16)
  42.         SerialUSB.print("0");
  43.       SerialUSB.print(address,HEX);
  44.       SerialUSB.println("  !");
  45.  
  46.       nDevices++;
  47.     }
  48.     else if (error==4)
  49.     {
  50.       SerialUSB.print("Unknown error at address 0x");
  51.       if (address<16)
  52.         SerialUSB.print("0");
  53.       SerialUSB.println(address,HEX);
  54.     }    
  55.   }
  56.   if (nDevices == 0)
  57.     SerialUSB.println("No I2C devices found\n");
  58.   else
  59.     SerialUSB.println("done\n");
  60.  
  61.   delay(5000);           // wait 5 seconds for next scan
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement