A place for all the arduino code I write.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.9 KiB

  1. /* --------------------------------------
  2. * i2c_scanner
  3. *
  4. * Version 1
  5. * This program (or code that looks like it)
  6. * can be found in many places.
  7. * For example on the Arduino.cc forum.
  8. * The original author is not know.
  9. * Version 2, Juni 2012, Using Arduino 1.0.1
  10. * Adapted to be as simple as possible by Arduino.cc user Krodal
  11. * Version 3, Feb 26 2013
  12. * V3 by louarnold
  13. * Version 4, March 3, 2013, Using Arduino 1.0.3
  14. * by Arduino.cc user Krodal.
  15. * Changes by louarnold removed.
  16. * Scanning addresses changed from 0...127 to 1...119,
  17. * according to the i2c scanner by Nick Gammon
  18. *
  19. * Version 5, March 28, 2013
  20. * As version 4, but address scans now to 127.
  21. * A sensor seems to use address 120.
  22. * Version 6, November 27, 2015.
  23. * Added waiting for the Leonardo serial communication.
  24. * This sketch tests the standard 7-bit addresses
  25. * Devices with higher bit address might not be seen properly.
  26. */
  27. #include <Wire.h>
  28. void setup()
  29. {
  30. Wire.begin();
  31. Serial.begin(9600);
  32. while (!Serial); // Leonardo: wait for serial monitor
  33. Serial.println("\r\nI2C Scanner");
  34. }
  35. void loop()
  36. {
  37. byte error, address;
  38. int nDevices;
  39. Serial.println("Scanning...");
  40. nDevices = 0;
  41. for(address = 1; address < 127; address++ )
  42. {
  43. // The i2c_scanner uses the return value of
  44. // the Write.endTransmisstion to see if
  45. // a device did acknowledge to the address.
  46. Wire.beginTransmission(address);
  47. error = Wire.endTransmission();
  48. if (error == 0)
  49. {
  50. Serial.print("I2C device found at address 0x");
  51. if (address<16)
  52. Serial.print("0");
  53. Serial.print(address,HEX);
  54. Serial.println(" !");
  55. nDevices++;
  56. }
  57. else if (error==4)
  58. {
  59. Serial.print("Unknown error at address 0x");
  60. if (address<16)
  61. Serial.print("0");
  62. Serial.println(address,HEX);
  63. }
  64. }
  65. if (nDevices == 0)
  66. Serial.println("No I2C devices found\n");
  67. else
  68. Serial.println("done\n");
  69. delay(5000); // wait 5 seconds for next scan
  70. }