6-Axis IMU

The LSM6DS integrates both a 3-Axis Accellerometer and a 3-Axis Gyroscope in its tiny 3mm x 2.5mm package!

Code

'''
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)

Last updated