PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
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.

79 lines
2.4KB

  1. // -------------------------------------------------------------------------------------------
  2. // I2C Bus Scanner
  3. // -------------------------------------------------------------------------------------------
  4. //
  5. // This creates an I2C master device which will scan the address space and report all
  6. // devices which ACK. It does not attempt to transfer data, it only reports which devices
  7. // ACK their address.
  8. //
  9. // Pull the control pin low to initiate the scan. Result will output to Serial.
  10. //
  11. // This example code is in the public domain.
  12. // -------------------------------------------------------------------------------------------
  13. #include <i2c_t3.h>
  14. // Function prototypes
  15. void print_scan_status(uint8_t target, uint8_t all);
  16. uint8_t found, target, all;
  17. void setup()
  18. {
  19. pinMode(LED_BUILTIN,OUTPUT); // LED
  20. pinMode(12,INPUT_PULLUP); // pull pin 12 low to show ACK only results
  21. pinMode(11,INPUT_PULLUP); // pull pin 11 low for a more verbose result (shows both ACK and NACK)
  22. // Setup for Master mode, pins 18/19, external pullups, 400kHz, 10ms default timeout
  23. Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, 400000);
  24. Wire.setDefaultTimeout(10000); // 10ms
  25. Serial.begin(115200);
  26. }
  27. void loop()
  28. {
  29. // Scan I2C addresses
  30. //
  31. if(digitalRead(12) == LOW || digitalRead(11) == LOW)
  32. {
  33. all = (digitalRead(11) == LOW);
  34. found = 0;
  35. Serial.print("---------------------------------------------------\n");
  36. Serial.print("Starting scan...\n");
  37. digitalWrite(LED_BUILTIN,HIGH); // LED on
  38. for(target = 1; target <= 0x7F; target++) // sweep addr, skip general call
  39. {
  40. Wire.beginTransmission(target); // slave addr
  41. Wire.endTransmission(); // no data, just addr
  42. print_scan_status(target, all);
  43. }
  44. digitalWrite(LED_BUILTIN,LOW); // LED off
  45. if(!found) Serial.print("No devices found.\n");
  46. delay(500); // delay to space out tests
  47. }
  48. }
  49. //
  50. // print scan status
  51. //
  52. void print_scan_status(uint8_t target, uint8_t all)
  53. {
  54. switch(Wire.status())
  55. {
  56. case I2C_WAITING:
  57. Serial.printf("Addr: 0x%02X ACK\n", target);
  58. found = 1;
  59. break;
  60. case I2C_ADDR_NAK:
  61. if(all) Serial.printf("Addr: 0x%02X\n", target);
  62. break;
  63. default:
  64. break;
  65. }
  66. }