microrobotics

Untitled

Jan 29th, 2026
3,146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Wire.h>
  2. #include <Adafruit_LSM9DS1.h>
  3. #include <Adafruit_Sensor.h>
  4.  
  5. Adafruit_LSM9DS1 lsm = Adafruit_LSM9DS1();
  6.  
  7. // ESP32 I2C pins (default)
  8. #define SDA_PIN 21
  9. #define SCL_PIN 22
  10.  
  11. void setup() {
  12.   Serial.begin(115200);
  13.   delay(1000);
  14.  
  15.   // Initialize I2C with ESP32 pins
  16.   Wire.begin(SDA_PIN, SCL_PIN);
  17.  
  18.   Serial.println("LSM9DS1 Test");
  19.  
  20.   // Initialize the sensor
  21.   if (!lsm.begin()) {
  22.     Serial.println("Failed to find LSM9DS1 chip");
  23.     while (1) {
  24.       delay(10);
  25.     }
  26.   }
  27.   Serial.println("LSM9DS1 Found!");
  28.  
  29.   // Setup sensor ranges
  30.   lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_2G);
  31.   lsm.setupMag(lsm.LSM9DS1_MAGGAIN_4GAUSS);
  32.   lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_245DPS);
  33.  
  34.   Serial.println("Sensor configured!");
  35. }
  36.  
  37. void loop() {
  38.   // Read sensor data
  39.   lsm.read();
  40.  
  41.   // Get sensor events
  42.   sensors_event_t accel, mag, gyro, temp;
  43.   lsm.getEvent(&accel, &mag, &gyro, &temp);
  44.  
  45.   // Print accelerometer data (m/s^2)
  46.   Serial.print("Accel X: "); Serial.print(accel.acceleration.x, 2);
  47.   Serial.print(" Y: "); Serial.print(accel.acceleration.y, 2);
  48.   Serial.print(" Z: "); Serial.print(accel.acceleration.z, 2);
  49.   Serial.print(" m/s^2 | ");
  50.  
  51.   // Print gyroscope data (rad/s)
  52.   Serial.print("Gyro X: "); Serial.print(gyro.gyro.x, 2);
  53.   Serial.print(" Y: "); Serial.print(gyro.gyro.y, 2);
  54.   Serial.print(" Z: "); Serial.print(gyro.gyro.z, 2);
  55.   Serial.print(" rad/s | ");
  56.  
  57.   // Print magnetometer data (gauss)
  58.   Serial.print("Mag X: "); Serial.print(mag.magnetic.x, 2);
  59.   Serial.print(" Y: "); Serial.print(mag.magnetic.y, 2);
  60.   Serial.print(" Z: "); Serial.println(mag.magnetic.z, 2);
  61.  
  62.   delay(100);
  63. }
  64. ```
  65.  
  66. // **Connections:**
  67. // GY-LSM9DS1  →  ESP32
  68. // VCC         →  3.3V
  69. // GND         →  GND
  70. // SDA         →  GPIO 21
  71. // SCL         →  GPIO 22
Advertisement