Code test I2C cho ESP32

24/09/2026

Code test I2C cho ESP32

Dùng đoạn code Arduino IDE này để quét I2C trên ESP32. Với BNO086 của bạn: SDA = GPIO21, SCL = GPIO22.

 
#include <Wire.h>

#define SDA_PIN 21
#define SCL_PIN 22

void setup()
{
  Serial.begin(115200);
  delay(1000);

  Serial.println();
  Serial.println("=== ESP32 I2C SCANNER ===");

  Wire.begin(SDA_PIN, SCL_PIN);
  Wire.setClock(100000);   // Test trước ở 100kHz

  Serial.println("SDA = GPIO21");
  Serial.println("SCL = GPIO22");
}

void loop()
{
  byte error;
  byte address;
  int devices = 0;

  Serial.println();
  Serial.println("Dang quet I2C...");

  for (address = 1; address < 127; address++)
  {
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("Tim thay I2C tai dia chi 0x");

      if (address < 16)
        Serial.print("0");

      Serial.println(address, HEX);
      devices++;
    }
    else if (error == 4)
    {
      Serial.print("Loi tai dia chi 0x");

      if (address < 16)
        Serial.print("0");

      Serial.println(address, HEX);
    }
  }

  if (devices == 0)
  {
    Serial.println("KHONG TIM THAY THIET BI I2C!");
  }
  else
  {
    Serial.print("Tong so thiet bi: ");
    Serial.println(devices);
  }

  Serial.println("-------------------------");

  delay(3000);
}

Đấu BNO086

BNO086          ESP32
----------------------
3V3    -------> 3.3V
GND    -------> GND
SDA    -------> GPIO21
SCL    -------> GPIO22

Sau khi upload, mở Serial Monitor = 115200 baud. Nếu kết nối đúng, bạn có thể thấy kiểu:

 
=== ESP32 I2C SCANNER ===
SDA = GPIO21
SCL = GPIO22

Dang quet I2C...
Tim thay I2C tai dia chi 0x4B
Tong so thiet bi: 1

Hoặc có thể ra 0x4A tùy cấu hình địa chỉ của BNO086.

Bình luận
Nội dung này chưa có bình luận, hãy gửi bình luận đầu tiên của bạn.
VIẾT BÌNH LUẬN CỦA BẠN