Home CodeCircuitpython Raspberry Pi Pico and LIS3MDL three-axis magnetic sensor circuitpython example

Raspberry Pi Pico and LIS3MDL three-axis magnetic sensor circuitpython example

by rp2040guy71

In this article we connect a LIS3MDL three-axis magnetic sensor.to a Raspberry Pi Pico running Circuitpython

Sensor Information

The LIS3MDL is an ultra-low-power high-performance three-axis magnetic sensor. The LIS3MDL has user-selectable full scales of ±4/±8/±12/±16 gauss.
The self-test capability allows the user to check the functioning of the sensor in the final application.
The device may be configured to generate interrupt signals for magnetic field detection.

The LIS3MDL includes an I2C serial bus interface that supports standard and fast mode (100 kHz and 400 kHz) and SPI serial standard interface.

The LIS3MDL is available in a small thin plastic land grid array package (LGA) and is guaranteed to operate over an extended temperature range of -40 °C to +85 °C.

Features

Wide supply voltage, 1.9 V to 3.6 V
Independent IO supply (1.8 V)
±4/±8/±12/±16 gauss selectable magnetic full scales
Continuous and single-conversion modes
16-bit data output
Interrupt generator
Self-test
I2C/SPI digital output interface
Power-down mode / low-power mode

Parts Required

 

Name Link
Pico Raspberry Pi Pico Development Board
LIS3MDL LIS3MDL Magnetometer Triaxial Magnetic Field / Acceleration Sensor Module
Connecting cables Aliexpress link

Amazon.com link

Ebay link

 

Schematic/Connection

Black for GND
Red for V+
Blue for SDA
Yellow for SCL

So color coded for ease of use, this layout shows a connection to the module

rp2040 and lis3mdl

rp2040 and lis3mdl

Code Example

I used Thonny for development

The following is based on a library , I copied the adafruit_LIS3MDL.mpy library for this device to the lib folder on my Raspberry Pi Pico – https://circuitpython.org/libraries

This is the basic example which comes with the library, my sensor had an I2C address of 0x1E. If your sensor has a different one then you will need to change that line

import time
import board
import adafruit_lis3mdl
import busio
 
i2c = busio.I2C(scl=board.GP1, sda=board.GP0) # uses board.SCL and board.SDA
 
sensor = adafruit_lis3mdl.LIS3MDL(i2c, 0x1E)
 
while True:
    mag_x, mag_y, mag_z = sensor.magnetic
 
    print("X:{0:10.2f}, Y:{1:10.2f}, Z:{2:10.2f} uT".format(mag_x, mag_y, mag_z))
    print("")
    time.sleep(1.0)

Output

Here is what I saw in Thonny REPL window

X: 3.33, Y: 6.64, Z: 118.08 uT

X: 10.29, Y: 2.25, Z: 115.70 uT

X: 9.47, Y: 49.91, Z: 121.43 uT

X: 22.43, Y: 10.70, Z: 114.44 uT

Links

https://www.st.com/resource/en/datasheet/lis3mdl.pdf

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More