跳到主要內容

 自 109 / 2 /25 起啟用

物聯網 / OLED / 掃瞄I2C設備的位址

掃瞄I2C設備的位址

下列程式是如果不知道手邊I2C設備的位址時,才需要下載至控制板中,

本程式是在掃瞄接在控制板上的I2C設備位址

 

  1. #include "Wire.h"
  2.  
  3. void setup()
  4. {
  5.   Wire.begin();
  6.   Serial.begin(9600);
  7.   while (!Serial);             // Leonardo: wait for serial monitor
  8.   Serial.println("nI2C Scanner");
  9. }
  10.  
  11. void loop()
  12. {
  13.   byte error, address;
  14.   int nDevices;
  15.   Serial.println("Scanning...");
  16.   nDevices = 0;
  17.   for(address = 1; address < 127; address++ )
  18.   {
  19.     // The i2c_scanner uses the return value of
  20.     // the Write.endTransmisstion to see if
  21.     // a device did acknowledge to the address.
  22.     Wire.beginTransmission(address);
  23.     error = Wire.endTransmission();
  24.  
  25.     if (error == 0)
  26.     {
  27.       Serial.print("I2C device found at address 0x");
  28.       if (address<16)
  29.         Serial.print("0");
  30.       Serial.print(address,HEX);
  31.       Serial.println("  !");
  32.       nDevices++;
  33.     }
  34.     else if (error==4)
  35.     {
  36.       Serial.print("Unknow error at address 0x");
  37.       if (address<16)
  38.         Serial.print("0");
  39.       Serial.println(address,HEX);
  40.     }    
  41.   }
  42.   if (nDevices == 0)
  43.     Serial.println("No I2C devices foundn");
  44.   else
  45.     Serial.println("donen");
  46.   delay(5000);           // wait 5 seconds for next scan
  47. }

 

消息公佈欄

時間類別單位標題發佈點閱
跳至網頁頂部