Example Code for Arduino-Reading Data via I2C

This tutorial guides you through initializing a 6-axis IMU sensor and reading accelerometer and gyroscope data using I2C polling. Ideal for tech enthusiasts looking to enhance their projects with precise motion sensing capabilities.

Hardware Preparation

Software Preparation

Wiring Diagram

SEN0693-I2C wiring diagram

Connect the 6-axis IMU sensor to the ESP32-C5 as shown in the diagram. The main connections are:

  • Sensor pin “3V3” → ESP32-C5 3.3V
  • Sensor pin “GND” → ESP32-C5 GND
  • Sensor I2C pin “SCL” → ESP32-C5 SCL (default GPIO10)
  • Sensor I2C pin “SDA” → ESP32-C5 SDA (default GPIO9)
  • I2C address pad configuration: Leave the pad open, the I2C address will be 0x69 (factory default mode)

Sample Code

#include "DFRobot_BMI323.h"

#define BMI323_I2C_ADDR 0x69    

DFRobot_BMI323 bmi323(&Wire, BMI323_I2C_ADDR);

void setup()
{
  Serial.begin(115200);
  while (!Serial) {
    delay(10);
  }

  Serial.println("BMI323 Six-Axis Data");
  Serial.println("====================");

  while (!bmi323.begin()) {
    Serial.println("Sensor init failed, please check wiring. Retry in 1s.");
    delay(1000);
  }

  if (!bmi323.configAccel(bmi323.eAccelODR50Hz, bmi323.eAccelRange8G, bmi323.eAccelModeNormal)) {
    Serial.println("Accel config failed!");
    while (1) {
      delay(1000);
    }
  }

  if (!bmi323.configGyro(bmi323.eGyroODR800Hz, bmi323.eGyroRange2000DPS, bmi323.eGyroModeNormal)) {
    Serial.println("Gyro config failed!");
    while (1) {
      delay(1000);
    }
  }

  delay(1000);
  Serial.println("Setup complete!\n");
}

void loop()
{
  DFRobot_BMI323::sSensorData accel;
  DFRobot_BMI323::sSensorData gyro;

  if (bmi323.getAccelGyroData(&accel, &gyro)) {
    Serial.print("Accel (g)  : ");
    Serial.print(accel.x, 3);
    Serial.print(", ");
    Serial.print(accel.y, 3);
    Serial.print(", ");
    Serial.println(accel.z, 3);

    Serial.print("Gyro (dps) : ");
    Serial.print(gyro.x, 2);
    Serial.print(", ");
    Serial.print(gyro.y, 2);
    Serial.print(", ");
    Serial.println(gyro.z, 2);
    Serial.println("---");
  } else {
    Serial.println("Failed to read sensor data.");
  }

  delay(200);
}

Result

SEN0693-I2C Result

Was this article helpful?

TOP