lsm303 — control of LSM303C/AGR accelerometer/magnetometer

This module provides classes to control an LSM303C/AGR combined accelerometer and magnetometer. It is used internally by the Kookaberry to provide access to the internal LSM303C/AGR, but can also be used to control an external LSM303C or LSM303AGR chip.

The LSM303C/AGR provides two independent I2C slaves for the accelerometer and magnetometer, with default I2C addresses of 0x1d and 0x1e respectively.

Example usage:

import lsm303
from machine import Pin, SoftI2C

i2c = SoftI2C(scl=Pin('P3A'), sda=Pin('P3B')) # Create I2C bus for an external LSM303C/AGR

accel = lsm303.LSM303C_Accel(i2c)
mag = lsm303.LSM303C_Mag(i2c)

print(accel.get_xyz(), mag.get_strength())

Class LSM303C_Accel

This class represents a connection to the accelerometer part of the LSM303C/AGR.

The Kookaberry’s internal accelerator has the name kooka.accel instead of LSM303_Accel.

LSM303_Accel Constructors

class lsm303.LSM303C_Accel(i2c, addr=0x1d)

Creates a new instance of this class.

i2c should be a machine.SoftI2C object. object that the LSM303C/AGR is connected to.

addr is the I2C address of the accelerometer, which defaults to 0x1d if not specified.

LSM303 Methods

LSM303C_Accel.get_xyz()

Returns the current x/y/z values of the accelerometer as a 3-tuple.

LSM303C_Accel.get_magnitude()

Returns the total (positive) magnitude of acceleration which is the vector sum of the x/y/z accelerations.

LSM303C_Accel.config(freq=50, range=2)

Configures the sampling frequency and the acceleration range of the accelerometer.

freq is the sampling frequency. Valid frequencies are: 10, 50 (default), 100, 200, and 400

range is the maximum acceleration able to be recorded. Valid ranges are 2 (default), 4 and 8

class LSM303C_Mag

This class represents a connection to the magnetometer part of the LSM303C/AGR.

The Kookaberry’s internal magnetometer has the name kooka.compass instead of LSM303_Mag.

LSM303C_Mag Constructors

class lsm303.LSM303C_Mag(i2c, addr=0x1e)

Creates a new instance of this class.

i2c should be a machine.SoftI2C object. that the LSM303C/AGR is connected to.

addr is the I2C address of the magnetometer, which defaults to 0x1e if not specified.

LSM303C_Mag Methods

LSM303C_Mag.get_xyz()

Returns the current x/y/z values of the magnetometer as a 3-tuple. These values are filtered with a moving average of the last 4 samples.

LSM303C_Mag.get_heading()

Returns a simple measure of the compass heading via the formula math.atan2(y, x).

LSM303C_Mag.get_strength()

Returns the (positive) magnitude of the 3-vector returned by LSM303C_Mag.get_xyz(), as an integer.