blimputils.magnetometer
magnetometer.py
Module for the Bosch-Sensortec BMM350 magnetometer. Provides class infrastructure and implementation of underlying methods for interacting with the sensor.
- class blimputils.magnetometer.bmm350_dut_offset_coef(t_offs: float, offset_x: float, offset_y: float, offset_z: float)
Bases:
object
BMM350 magnetometer DUT offset coefficient structure.
Stores temperature and XYZ offset coefficients.
- Parameters:
t_offs (float) – Temperature offset coefficient.
offset_x (float) – X-axis offset coefficient.
offset_y (float) – Y-axis offset coefficient.
offset_z (float) – Z-axis offset coefficient.
- class blimputils.magnetometer.bmm350_dut_sensit_coef(t_sens: float, sens_x: float, sens_y: float, sens_z: float)
Bases:
object
BMM350 magnetometer DUT sensitivity coefficient structure.
Stores temperature and XYZ sensitivity coefficients.
- Parameters:
t_sens (float) – Temperature sensitivity coefficient.
sens_x (float) – X-axis sensitivity coefficient.
sens_y (float) – Y-axis sensitivity coefficient.
sens_z (float) – Z-axis sensitivity coefficient.
- class blimputils.magnetometer.bmm350_dut_tco(tco_x: float, tco_y: float, tco_z: float)
Bases:
object
BMM350 magnetometer DUT TCO (Temperature Coefficient of Offset) structure.
Stores TCO coefficients for X, Y, and Z axes.
- Parameters:
tco_x (float) – X-axis TCO coefficient.
tco_y (float) – Y-axis TCO coefficient.
tco_z (float) – Z-axis TCO coefficient.
- class blimputils.magnetometer.bmm350_dut_tcs(tcs_x: float, tcs_y: float, tcs_z: float)
Bases:
object
BMM350 magnetometer DUT TCS (Temperature Coefficient of Sensitivity) structure.
Stores TCS coefficients for X, Y, and Z axes.
- Parameters:
tcs_x (float) – X-axis TCS coefficient.
tcs_y (float) – Y-axis TCS coefficient.
tcs_z (float) – Z-axis TCS coefficient.
- class blimputils.magnetometer.bmm350_cross_axis(cross_x_y: float, cross_y_x: float, cross_z_x: float, cross_z_y: float)
Bases:
object
BMM350 magnetometer cross-axis compensation structure.
Stores cross-axis sensitivity coefficients.
- Parameters:
cross_x_y (float) – Cross-axis sensitivity from Y to X.
cross_y_x (float) – Cross-axis sensitivity from X to Y.
cross_z_x (float) – Cross-axis sensitivity from X to Z.
cross_z_y (float) – Cross-axis sensitivity from Y to Z.
- class blimputils.magnetometer.bmm350_mag_compensate(dut_offset_coef: bmm350_dut_offset_coef, dut_sensit_coef: bmm350_dut_sensit_coef, dut_tco: bmm350_dut_tco, dut_tcs: bmm350_dut_tcs, dut_t0: float, cross_axis: bmm350_cross_axis)
Bases:
object
BMM350 magnetometer compensation data structure.
Holds all compensation coefficients required for sensor data correction.
- Parameters:
dut_offset_coef (bmm350_dut_offset_coef) – DUT offset coefficients.
dut_sensit_coef (bmm350_dut_sensit_coef) – DUT sensitivity coefficients.
dut_tco (bmm350_dut_tco) – DUT TCO coefficients.
dut_tcs (bmm350_dut_tcs) – DUT TCS coefficients.
dut_t0 (float) – DUT T0 (reference temperature).
cross_axis (bmm350_cross_axis) – Cross-axis compensation coefficients.
- class blimputils.magnetometer.bmm350_dev(mag_comp: bmm350_mag_compensate)
Bases:
object
BMM350 device structure.
Represents the BMM350 sensor device, including its chip ID, OTP data, compensation data, power mode, and enabled axes.
- Parameters:
mag_comp (bmm350_mag_compensate) – Magnetometer compensation data.
- class blimputils.magnetometer.BMM350RawMagData
Bases:
object
Structure to hold uncompensated (raw) BMM350 magnetometer and temperature data.
Used internally to store raw ADC counts before any compensation or scaling.
- class blimputils.magnetometer.BMM350MagData
Bases:
object
Structure to hold compensated BMM350 magnetometer and temperature data.
Stores the final X, Y, Z magnetic field values (typically in µT) and the temperature (typically in °C) after all compensations.
- class blimputils.magnetometer.bmm350_pmu_cmd_status_0(pmu_cmd_busy, odr_ovwr, avr_ovwr, pwr_mode_is_normal, cmd_is_illegal, pmu_cmd_value)
Bases:
object
BMM350 PMU (Power Management Unit) command status 0 register structure.
Decodes the bits of the PMU_CMD_STATUS_0 register.
- Parameters:
pmu_cmd_busy (int) – PMU command busy status.
odr_ovwr (int) – ODR (Output Data Rate) overwrite status.
avr_ovwr (int) – Averaging overwrite status.
pwr_mode_is_normal (int) – Power mode is normal status.
cmd_is_illegal (int) – Command is illegal status.
pmu_cmd_value (int) – PMU command value.
- class blimputils.magnetometer.Magnetometer(bus=1, addr=20)
Bases:
object
Bosch BMM350 Magnetometer sensor class.
Provides methods to initialize, configure, and read data from the BMM350 sensor using I2C communication. This class handles low-level register interactions, OTP data loading, power mode management, and data compensation.
- Parameters:
bus (int) – The I2C bus number (e.g., 1 for Raspberry Pi’s /dev/i2c-1).
addr (int) – The I2C address of the BMM350 sensor. Defaults to
BMM350_I2C_ADDRESS_PRIMARY
if not provided, but typically specified during instantiation.
- I2C_MODE = 1
- BMM350_SET_BITS(reg_data, bitname_msk, bitname_pos, data)
Set specific bits in a register value.
- Parameters:
reg_data (int) – The original register value.
bitname_msk (int) – The mask for the bits to be set.
bitname_pos (int) – The starting position of the bits.
data (int) – The data to write to the specified bits.
- Returns:
The modified register value.
- Return type:
int
- BMM350_GET_BITS(reg_data, mask, pos)
Get specific bits from a register value.
- Parameters:
reg_data (int) – The register value.
mask (int) – The mask for the bits to be retrieved.
pos (int) – The starting position of the bits.
- Returns:
The value of the specified bits.
- Return type:
int
- BMM350_GET_BITS_POS_0(reg_data, mask)
Get specific bits from a register value, assuming bit position 0.
- Parameters:
reg_data (int) – The register value.
mask (int) – The mask for the bits to be retrieved.
- Returns:
The value of the specified bits.
- Return type:
int
- BMM350_SET_BITS_POS_0(reg_data, mask, data)
Set specific bits in a register value, assuming bit position 0.
- Parameters:
reg_data (int) – The original register value.
mask (int) – The mask for the bits to be set.
data (int) – The data to write to the specified bits.
- Returns:
The modified register value.
- Return type:
int
- fix_sign(inval, number_of_bits)
Convert raw data from IC data registers to a signed integer.
This internal API handles the conversion of unsigned ADC values to signed integer representations based on the number of bits.
- Parameters:
inval (int) – The input unsigned integer value.
number_of_bits (int) – The number of bits representing the signed integer.
- Options number_of_bits:
BMM350_SIGNED_8_BIT
BMM350_SIGNED_12_BIT
BMM350_SIGNED_16_BIT
BMM350_SIGNED_21_BIT
BMM350_SIGNED_24_BIT
- Returns:
The signed integer value.
- Return type:
int
- update_mag_off_sens()
Update magnetometer offset and sensitivity data from OTP values.
This internal API reads the OTP (One-Time Programmable) memory data and populates the compensation structures (bmm350_sensor.mag_comp) with offset, sensitivity, TCO, TCS, T0, and cross-axis coefficients.
- bmm350_set_powermode(powermode)
Set the power mode of the BMM350 sensor.
Transitions the sensor to the specified power mode (Suspend, Normal, Forced, Forced Fast). Includes necessary delays for mode transitions.
- Parameters:
powermode (int) – The desired power mode.
- Options powermode:
BMM350_SUSPEND_MODE
BMM350_NORMAL_MODE
BMM350_FORCED_MODE
BMM350_FORCED_MODE_FAST
- bmm350_magnetic_reset_and_wait()
Perform a magnetic reset sequence and wait for completion.
This sequence involves transitioning to suspend mode, issuing magnetic reset commands (BR and FGR), and then optionally restoring the previous normal mode if it was active.
- sensor_init()
Initialize the BMM350 sensor.
Performs a software reset, verifies the chip ID, downloads OTP compensation data, updates internal compensation parameters, and performs a magnetic reset.
- Returns:
Status of the initialization.
- Return type:
int
- Retval:
BMM350_OK: Initialization successful.
- Retval:
BMM350_CHIP_ID_ERROR: Chip ID mismatch, initialization failed.
- get_chip_id()
Read the chip ID from the BMM350 sensor.
- Returns:
The chip ID value.
- Return type:
int
- soft_reset()
Perform a soft reset on the BMM350 sensor.
Restores the sensor to suspend mode after the soft reset. This involves issuing a soft reset command, disabling OTP, performing a magnetic reset, and finally setting the power mode to suspend. The user needs to manually set the desired operation mode afterwards.
- set_operation_mode(modes)
Set the sensor operation mode.
Allows switching between suspend, normal, forced, and forced-fast modes.
- Parameters:
modes (int) – The desired operation mode.
- Options modes:
BMM350_SUSPEND_MODE
: Suspend mode. Minimal current consumption.All registers are accessible. Default after power-on.
BMM350_NORMAL_MODE
: Normal mode. Continuous measurement at the configured ODR.BMM350_FORCED_MODE
: Forced mode. Single measurement, then returns to suspend mode.BMM350_FORCED_MODE_FAST
: Forced mode fast. Single measurement with faster ODR capability (up to 200Hz), then returns to suspend mode.
- get_operation_mode()
Get the current sensor operation mode.
- Returns:
A string describing the current operation mode.
- Return type:
str
- Retval:
“bmm350 is suspend mode!”: Sensor is in suspend mode.
- Retval:
“bmm350 is normal mode!”: Sensor is in normal mode.
- Retval:
“bmm350 is forced mode!”: Sensor is in forced mode.
- Retval:
“bmm350 is forced_fast mode!”: Sensor is in forced-fast mode.
- Retval:
“error mode!”: Unknown or error in power mode status.
- set_rate(rates)
Set the data output rate (ODR) for geomagnetic data.
The ODR determines how frequently new data is available from the sensor when in normal mode.
- Parameters:
rates (int) – The desired data rate identifier.
- Options rates:
BMM350_DATA_RATE_1_5625HZ
(1.5625 Hz)BMM350_DATA_RATE_3_125HZ
(3.125 Hz)BMM350_DATA_RATE_6_25HZ
(6.25 Hz)BMM350_DATA_RATE_12_5HZ
(12.5 Hz, default rate)BMM350_DATA_RATE_25HZ
(25 Hz)BMM350_DATA_RATE_50HZ
(50 Hz)BMM350_DATA_RATE_100HZ
(100 Hz)BMM350_DATA_RATE_200HZ
(200 Hz)BMM350_DATA_RATE_400HZ
(400 Hz)
- get_rate()
Get the configured data output rate (ODR).
- Returns:
The current ODR in Hertz (Hz).
- Return type:
float
- set_preset_mode(avg, odr=7)
Set a preset measurement mode combining averaging and ODR.
This simplifies sensor configuration for common use cases by setting the number of averages and the output data rate.
- Parameters:
avg (int) – The averaging setting (number of measurements to average).
odr (int, optional) – The desired data output rate. Defaults to
BMM350_DATA_RATE_12_5HZ
.
- Options avg:
BMM350_AVERAGING_NO_AVG
(No averaging)BMM350_AVERAGING_2_AVG
(2 averages)BMM350_AVERAGING_4_AVG
(4 averages)BMM350_AVERAGING_8_AVG
(8 averages)
- Options odr:
BMM350_DATA_RATE_1_5625HZ
BMM350_DATA_RATE_3_125HZ
BMM350_DATA_RATE_6_25HZ
BMM350_DATA_RATE_12_5HZ
BMM350_DATA_RATE_25HZ
BMM350_DATA_RATE_50HZ
BMM350_DATA_RATE_100HZ
BMM350_DATA_RATE_200HZ
BMM350_DATA_RATE_400HZ
- self_test()
Perform a sensor self-test by checking enabled axes.
This method reads the axis enable register and reports which axes (X, Y, Z) are currently enabled for measurement. It does not perform a full functional self-test of the sensor hardware.
- Returns:
A string indicating the self-test result based on enabled axes.
- Return type:
str
- Retval:
“x y z aix test success”: If X, Y, and Z axes are enabled.
- Retval:
“<axes> aix test success”: If a subset of axes are enabled (e.g., “x y “).
- Retval:
“xyz aix self test fail”: If no axes are enabled.
- set_measurement_XYZ(en_x=1, en_y=1, en_z=1)
Enable or disable measurements for X, Y, and Z axes.
Allows individual control over which magnetic axes are active. Disabling an axis will result in invalid data for that axis.
- Parameters:
en_x (int, optional) – Enable state for the X-axis. Defaults to
BMM350_X_EN
.en_y (int, optional) – Enable state for the Y-axis. Defaults to
BMM350_Y_EN
.en_z (int, optional) – Enable state for the Z-axis. Defaults to
BMM350_Z_EN
.
- Options en_x:
BMM350_X_EN
: Enable X-axis measurement.BMM350_X_DIS
: Disable X-axis measurement.
- Options en_y:
BMM350_Y_EN
: Enable Y-axis measurement.BMM350_Y_DIS
: Disable Y-axis measurement.
- Options en_z:
BMM350_Z_EN
: Enable Z-axis measurement.BMM350_Z_DIS
: Disable Z-axis measurement.
- get_measurement_state_XYZ()
Get the current enable status for X, Y, and Z axes measurements.
- Returns:
A string describing the enable status of each axis.
- Return type:
str
- Retval:
“x-axis enabled, y-axis enabled, z-axis enabled.”
- Retval:
“x-axis disabled, y-axis disabled, z-axis disabled.”
- get_raw_magnetic_data_for_calibration()
Get raw X, Y, Z magnetic data before OTP and software compensations.
This method reads the raw 24-bit ADC values for the X, Y, and Z magnetic axes. It is intended for use during sensor calibration procedures to collect uncompensated data.
- Returns:
A list containing the raw signed integer values for [X, Y, Z]. Returns
None
if the read operation fails or returns insufficient data.- Return type:
list[int] or None
- get_xyz()
Get calibrated geomagnetic data (X, Y, Z) in microTeslas (µT) and update sensor temperature.
This method performs the following steps:
Reads raw 24-bit data for X, Y, Z magnetic axes and temperature.
Applies sign correction to the raw data.
Stores raw LSB values in _raw_mag_data.
Applies user-defined hard iron calibration offsets (_CALIBRATION_HARD_IRON).
Applies user-defined soft iron calibration transformation (_CALIBRATION_SOFT_IRON_TRANSFORM).
Scales the corrected vector to physical units (µT) using _LOCAL_EARTH_FIELD_UT.
Stores the final calibrated X, Y, Z values in _mag_data.
Calculates and updates the sensor temperature in _mag_data.temperature using OTP compensation values.
- return:
List containing calibrated [X_µT, Y_µT, Z_µT]. Returns a list of
BMM350_FLOAT_DATA_ERROR
(e.g., float(‘nan’)) for each component on failure to read sensor data.- rtype:
list[float]
- get_x()
Get the calibrated X-axis geomagnetic data.
This is a convenience method that calls get_xyz and returns only the X component.
- Returns:
Calibrated X-axis magnetic field strength in microTeslas (µT). Returns
BMM350_FLOAT_DATA_ERROR
if data retrieval fails.- Return type:
float
- get_y()
Get the calibrated Y-axis geomagnetic data.
This is a convenience method that calls get_xyz and returns only the Y component.
- Returns:
Calibrated Y-axis magnetic field strength in microTeslas (µT). Returns
BMM350_FLOAT_DATA_ERROR
if data retrieval fails.- Return type:
float
- get_z()
Get the calibrated Z-axis geomagnetic data.
This is a convenience method that calls get_xyz and returns only the Z component.
- Returns:
Calibrated Z-axis magnetic field strength in microTeslas (µT). Returns
BMM350_FLOAT_DATA_ERROR
if data retrieval fails.- Return type:
float
- get_t()
Get the sensor temperature.
This is a convenience method that calls get_xyz (which also calculates temperature) and returns the temperature.
- Returns:
Sensor temperature in degrees Celsius (°C). Returns
BMM350_FLOAT_DATA_ERROR
if data retrieval fails.- Return type:
float
- get_compass_degree()
Get compass degree (yaw/heading) assuming the sensor’s XY plane is horizontal.
Calculates the yaw angle based on the calibrated X and Y geomagnetic components. The angle is measured counter-clockwise from the sensor’s positive X-axis to the projection of the magnetic field vector in the XY plane.
Note
This calculation is not tilt-compensated; To derive True North heading, apply your real-world declination constant post-function call.
Warning
This function is still in development, due to the complexity associated with hard-iron, soft-iron, and tilt compensation calibration.
- Returns:
Compass degree (0.0 to 360.0 degrees). Returns
BMM350_FLOAT_DATA_ERROR
(e.g., float(‘nan’)) if magnetometer data is invalid.- Return type:
float
- set_data_ready_pin(modes, polarity)
Configure the Data Ready (DRDY) interrupt pin.
Enables or disables the DRDY interrupt and sets its polarity. When enabled, the DRDY pin signals when new data is available.
- Parameters:
modes (int) – Enable or disable the DRDY interrupt.
polarity (int) – Polarity of the DRDY interrupt pin.
- Options modes:
BMM350_ENABLE_INTERRUPT
: Enable DRDY interrupt.BMM350_DISABLE_INTERRUPT
: Disable DRDY interrupt.
- Options polarity:
BMM350_ACTIVE_HIGH
: Active high polarity. Pin goes high on interrupt.BMM350_ACTIVE_LOW
: Active low polarity. Pin goes low on interrupt.
- get_data_ready_state()
Get the data ready status from the interrupt status register.
Checks if the DRDY (Data Ready) bit is set, indicating new data is available.
- Returns:
True
if data is ready,False
otherwise.- Return type:
bool
- set_threshold_interrupt(modes, threshold, polarity)
Configure the threshold interrupt.
Sets up an interrupt that triggers when the geomagnetic value of a channel crosses a defined threshold (either low or high). The threshold value is effectively scaled by 16 internally.
- Parameters:
modes (int) – The type of threshold interrupt.
threshold (int or float) – The threshold value. The actual trigger threshold will be threshold * 16.
polarity (int) – Polarity of the interrupt pin.
- Options modes:
LOW_THRESHOLD_INTERRUPT
: Interrupt when data is below the threshold.HIGH_THRESHOLD_INTERRUPT
: Interrupt when data is above the threshold (Note: current implementation logic for HIGH seems same as LOW, review needed).
- Options polarity:
POLARITY_HIGH
(orBMM350_ACTIVE_HIGH
): Active high.POLARITY_LOW
(orBMM350_ACTIVE_LOW
): Active low.
- get_threshold_data()
Get the data that caused a threshold interrupt.
If a threshold interrupt has occurred (checked via get_data_ready_state), this method returns the geomagnetic data components (X, Y, Z) that crossed the configured threshold.
- Returns:
A list of three elements. Each element is the magnetic data for an axis (X, Y, Z) if it triggered the interrupt, otherwise it’s
NO_DATA
. Example: [mag_x, NO_DATA, mag_z] if X and Z triggered the interrupt.- Return type:
list[float or int]
- is_raspberrypi()
Check if the current platform is a Raspberry Pi.
- Returns:
True
if a Raspberry Pi is detected,False
otherwise.- Return type:
bool
- test_platform()
Detects the platform (Linux or Windows) and initializes the I2C bus accordingly.
For Linux, it attempts to find an i2c-tiny-usb adapter if a standard bus is not found. For Windows, it uses i2c_mp_usb. Prints a message if the platform is not supported.
- write_reg(reg, data)
Writes a byte of data to a specified register.
Handles I2C communication errors by printing a message and retrying after a delay.
- Parameters:
reg (int) – The register address to write to.
data (int) – The byte of data to write.
- read_reg(reg, len)
Reads a specified number of bytes from a register.
Handles I2C communication, including dummy bytes if required by the BMM350 protocol. Retries on exception.
- Parameters:
reg (int) – The register address to read from.
len (int) – The number of bytes to read (excluding dummy bytes).
- Returns:
A list of bytes read from the register.
- Return type:
list[int]