# 6-Axis IMU

<div data-full-width="false"><figure><img src="/files/qnjDJ99y9NLFXJqLqA2o" alt=""><figcaption></figcaption></figure></div>

## Code

```python
'''
Raspberry Breadstick LSM6DS 6-Axis IMU (Gyroscope + Accelerometer)
May 28, 2024
Breadstick Innovations

When reset, the board takes 100 readings and averages them to calibrate
IMU offsets; the device must be flat on the table for this.
After calibration, tuples will be printed every 50ms, to be viewed
in Mu's plotter.
'''

from board import *
from time import sleep
import busio
from adafruit_lsm6ds.lsm6ds3trc import LSM6DS3TRC as LSM6DS
from adafruit_lsm6ds import Rate, AccelRange, GyroRange

i2c = busio.I2C(IMU_SCL, IMU_SDA)

# Setup I2C Accelerometer and Gyroscope
IMU = LSM6DS(i2c)
IMU.accelerometer_range = AccelRange.RANGE_4G
print("Accelerometer range set to: %d G" % AccelRange.string[IMU.accelerometer_range])
IMU.gyro_range = GyroRange.RANGE_1000_DPS
print("Gyro range set to: %d DPS" % GyroRange.string[IMU.gyro_range])
IMU.accelerometer_data_rate = Rate.RATE_1_66K_HZ
print("Accelerometer rate set to: %d HZ" % Rate.string[IMU.accelerometer_data_rate])
IMU.gyro_data_rate = Rate.RATE_1_66K_HZ
print("Gyro rate set to: %d HZ" % Rate.string[IMU.gyro_data_rate])

#Collect samples for calibration
#Device must remain perfectly still during calibration
num_samples = 100
accel_bias = [0,0,0]
gyro_bias = [0,0,0]
for i in range(num_samples):
    ax, ay,az = IMU.acceleration
    gx,gy,gz = IMU.gyro
    accel_bias[0] += ax
    accel_bias[1] += ay
    accel_bias[2] += az - 9.81
    gyro_bias[0] += gx
    gyro_bias[1] += gy
    gyro_bias[2] += gz

# Average the bias values
accel_bias = [total / num_samples for total in accel_bias]
gyro_bias = [total / num_samples for total in gyro_bias]

bax, bay, baz = accel_bias
bgx, bgy, bgz = gyro_bias

print('IMU calibration complete')
print(f'Accelerometer Offsets:\tX:{bax}\tY:{bay}\tZ:{baz}')
print(f'Gyroscope Offsets:\tX:{bgx}\tY:{bgy}\tZ:{bgz}')
sleep(5)

while True:
    ax, ay,az = IMU.acceleration
    gx,gy,gz = IMU.gyro
    ax -= bax
    ay -= bay
    az -= baz
    gx -= bgx
    gy -= bgy
    gz -= bgz
    
    print((ax,ay,az,gx,gy,gz))
    sleep(0.05)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learn.breadstick.ca/breadstick/breadsticks/raspberry-breadstick/code-examples/6-axis-imu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
