Skip to content

Commit dd97da8

Browse files
authored
Merge pull request #1 from adafruit/init_lib
library, example and docs
2 parents db75f35 + 663419a commit dd97da8

File tree

6 files changed

+335
-17
lines changed

6 files changed

+335
-17
lines changed

README.rst

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,22 @@ Usage Example
9494

9595
.. code-block:: python
9696
97+
import time
9798
import board
9899
import adafruit_qmc5883p
99100
101+
i2c = board.I2C()
102+
103+
sensor = adafruit_qmc5883p.QMC5883P(i2c)
104+
105+
while True:
106+
mag_x, mag_y, mag_z = sensor.magnetic
107+
108+
print(f"X:{mag_x:2.3f}, Y:{mag_y:2.3f}, Z:{mag_z:2.3f} G")
109+
print("")
110+
111+
time.sleep(1)
112+
100113
Documentation
101114
=============
102115
API documentation for this library can be found on `Read the Docs <https://docs.circuitpython.org/projects/qmc5883p/en/latest/>`_.

adafruit_qmc5883p.py

Lines changed: 288 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
21
# SPDX-FileCopyrightText: Copyright (c) 2025 Liz Clark for Adafruit Industries
32
#
43
# SPDX-License-Identifier: MIT
@@ -16,22 +15,302 @@
1615
1716
**Hardware:**
1817
19-
.. todo:: Add links to any specific hardware product page(s), or category page(s).
20-
Use unordered list & hyperlink rST inline format: "* `Link Text <url>`_"
18+
* `Adafruit QMC5883P - Triple Axis Magnetometer <https://www.adafruit.com/product/6388>`_"
2119
2220
**Software and Dependencies:**
2321
2422
* Adafruit CircuitPython firmware for the supported boards:
2523
https://circuitpython.org/downloads
2624
27-
.. todo:: Uncomment or remove the Bus Device and/or the Register library dependencies
28-
based on the library's use of either.
29-
30-
# * Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
31-
# * Adafruit's Register library: https://github.com/adafruit/Adafruit_CircuitPython_Register
25+
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
26+
* Adafruit's Register library: https://github.com/adafruit/Adafruit_CircuitPython_Register
3227
"""
3328

34-
# imports
29+
import struct
30+
import time
31+
32+
from adafruit_bus_device.i2c_device import I2CDevice
33+
from adafruit_register.i2c_bit import ROBit, RWBit
34+
from adafruit_register.i2c_bits import RWBits
35+
from adafruit_register.i2c_struct import ROUnaryStruct
36+
from micropython import const
37+
38+
try:
39+
from typing import Tuple
40+
41+
import busio
42+
except ImportError:
43+
pass
3544

3645
__version__ = "0.0.0+auto.0"
3746
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_QMC5883P.git"
47+
48+
# I2C Address
49+
_DEFAULT_ADDR = const(0x2C)
50+
51+
# Registers
52+
_CHIPID = const(0x00)
53+
_XOUT_LSB = const(0x01)
54+
_XOUT_MSB = const(0x02)
55+
_YOUT_LSB = const(0x03)
56+
_YOUT_MSB = const(0x04)
57+
_ZOUT_LSB = const(0x05)
58+
_ZOUT_MSB = const(0x06)
59+
_STATUS = const(0x09)
60+
_CONTROL1 = const(0x0A)
61+
_CONTROL2 = const(0x0B)
62+
63+
# Operating modes
64+
MODE_SUSPEND = const(0x00)
65+
MODE_NORMAL = const(0x01)
66+
MODE_SINGLE = const(0x02)
67+
MODE_CONTINUOUS = const(0x03)
68+
69+
# Output data rates
70+
ODR_10HZ = const(0x00)
71+
ODR_50HZ = const(0x01)
72+
ODR_100HZ = const(0x02)
73+
ODR_200HZ = const(0x03)
74+
75+
# Over sample ratios
76+
OSR_8 = const(0x00)
77+
OSR_4 = const(0x01)
78+
OSR_2 = const(0x02)
79+
OSR_1 = const(0x03)
80+
81+
# Downsample ratios
82+
DSR_1 = const(0x00)
83+
DSR_2 = const(0x01)
84+
DSR_4 = const(0x02)
85+
DSR_8 = const(0x03)
86+
87+
# Field ranges
88+
RANGE_30G = const(0x00)
89+
RANGE_12G = const(0x01)
90+
RANGE_8G = const(0x02)
91+
RANGE_2G = const(0x03)
92+
93+
# Set/Reset modes
94+
SETRESET_ON = const(0x00)
95+
SETRESET_SETONLY = const(0x01)
96+
SETRESET_OFF = const(0x02)
97+
98+
# LSB per Gauss for each range
99+
_LSB_PER_GAUSS = {RANGE_30G: 1000.0, RANGE_12G: 2500.0, RANGE_8G: 3750.0, RANGE_2G: 15000.0}
100+
101+
102+
class QMC5883P:
103+
"""Driver for the QMC5883P 3-axis magnetometer.
104+
105+
:param ~busio.I2C i2c_bus: The I2C bus the QMC5883P is connected to.
106+
:param int address: The I2C address of the device. Defaults to :const:`0x3C`
107+
"""
108+
109+
# Register definitions using adafruit_register
110+
_chip_id = ROUnaryStruct(_CHIPID, "<B")
111+
112+
# Status register bits
113+
data_ready = ROBit(_STATUS, 0)
114+
"""Check if new magnetic data is ready."""
115+
overflow = ROBit(_STATUS, 1)
116+
"""Check if data overflow has occurred."""
117+
118+
# Control register 1 bits
119+
_mode = RWBits(2, _CONTROL1, 0)
120+
_odr = RWBits(2, _CONTROL1, 2)
121+
_osr = RWBits(2, _CONTROL1, 4)
122+
_dsr = RWBits(2, _CONTROL1, 6)
123+
124+
# Control register 2 bits
125+
_setreset = RWBits(2, _CONTROL2, 0)
126+
_range = RWBits(2, _CONTROL2, 2)
127+
_selftest = RWBit(_CONTROL2, 6)
128+
_reset = RWBit(_CONTROL2, 7)
129+
130+
def __init__(self, i2c_bus: busio.I2C, address: int = _DEFAULT_ADDR) -> None:
131+
self.i2c_device = I2CDevice(i2c_bus, address)
132+
133+
# Check chip ID
134+
if self._chip_id != 0x80:
135+
raise RuntimeError("Failed to find QMC5883P chip")
136+
137+
# Initialize with default settings
138+
self.mode = MODE_NORMAL
139+
self.data_rate = ODR_50HZ
140+
self.oversample_ratio = OSR_4
141+
self.downsample_ratio = DSR_2
142+
self.range = RANGE_8G
143+
self.setreset_mode = SETRESET_ON
144+
145+
@property
146+
def magnetic(self) -> Tuple[float, float, float]:
147+
"""The magnetic field measured in microteslas (uT).
148+
149+
:return: A 3-tuple of X, Y, Z axis values in microteslas
150+
"""
151+
# Wait for data ready
152+
while not self.data_ready:
153+
time.sleep(0.001)
154+
155+
# Read all 6 bytes at once
156+
buf = bytearray(6)
157+
with self.i2c_device as i2c:
158+
i2c.write_then_readinto(bytes([_XOUT_LSB]), buf)
159+
160+
# Unpack as signed 16-bit integers
161+
raw_x, raw_y, raw_z = struct.unpack("<hhh", buf)
162+
163+
# Get conversion factor based on current range
164+
lsb_per_gauss = _LSB_PER_GAUSS[self._range]
165+
166+
# Convert to Gauss then to microteslas (1 Gauss = 100 uT)
167+
x = raw_x / lsb_per_gauss
168+
y = raw_y / lsb_per_gauss
169+
z = raw_z / lsb_per_gauss
170+
171+
return (x, y, z)
172+
173+
@property
174+
def magnetic_raw(self) -> Tuple[int, int, int]:
175+
"""The raw magnetic field sensor values as signed 16-bit integers.
176+
177+
:return: A 3-tuple of X, Y, Z axis raw values
178+
"""
179+
# Wait for data ready
180+
while not self._data_ready:
181+
time.sleep(0.001)
182+
183+
# Read all 6 bytes at once
184+
buf = bytearray(6)
185+
with self.i2c_device as i2c:
186+
i2c.write_then_readinto(bytes([_XOUT_LSB]), buf)
187+
188+
# Unpack as signed 16-bit integers
189+
return struct.unpack("<hhh", buf)
190+
191+
@property
192+
def mode(self) -> int:
193+
"""The operating mode of the sensor.
194+
195+
Options are:
196+
- MODE_SUSPEND (0x00): Suspend mode
197+
- MODE_NORMAL (0x01): Normal mode
198+
- MODE_SINGLE (0x02): Single measurement mode
199+
- MODE_CONTINUOUS (0x03): Continuous mode
200+
"""
201+
return self._mode
202+
203+
@mode.setter
204+
def mode(self, value: int) -> None:
205+
if value not in {MODE_SUSPEND, MODE_NORMAL, MODE_SINGLE, MODE_CONTINUOUS}:
206+
raise ValueError("Invalid mode")
207+
self._mode = value
208+
209+
@property
210+
def data_rate(self) -> int:
211+
"""The output data rate in Hz.
212+
213+
Options are:
214+
- ODR_10HZ (0x00): 10 Hz
215+
- ODR_50HZ (0x01): 50 Hz
216+
- ODR_100HZ (0x02): 100 Hz
217+
- ODR_200HZ (0x03): 200 Hz
218+
"""
219+
return self._odr
220+
221+
@data_rate.setter
222+
def data_rate(self, value: int) -> None:
223+
if value not in {ODR_10HZ, ODR_50HZ, ODR_100HZ, ODR_200HZ}:
224+
raise ValueError("Invalid output data rate")
225+
self._odr = value
226+
227+
@property
228+
def oversample_ratio(self) -> int:
229+
"""The over sample ratio.
230+
231+
Options are:
232+
- OSR_8 (0x00): Over sample ratio = 8
233+
- OSR_4 (0x01): Over sample ratio = 4
234+
- OSR_2 (0x02): Over sample ratio = 2
235+
- OSR_1 (0x03): Over sample ratio = 1
236+
"""
237+
return self._osr
238+
239+
@oversample_ratio.setter
240+
def oversample_ratio(self, value: int) -> None:
241+
if value not in {OSR_8, OSR_4, OSR_2, OSR_1}:
242+
raise ValueError("Invalid oversample ratio")
243+
self._osr = value
244+
245+
@property
246+
def downsample_ratio(self) -> int:
247+
"""The downsample ratio.
248+
249+
Options are:
250+
- DSR_1 (0x00): Downsample ratio = 1
251+
- DSR_2 (0x01): Downsample ratio = 2
252+
- DSR_4 (0x02): Downsample ratio = 4
253+
- DSR_8 (0x03): Downsample ratio = 8
254+
"""
255+
return self._dsr
256+
257+
@downsample_ratio.setter
258+
def downsample_ratio(self, value: int) -> None:
259+
if value not in {DSR_1, DSR_2, DSR_4, DSR_8}:
260+
raise ValueError("Invalid downsample ratio")
261+
self._dsr = value
262+
263+
@property
264+
def range(self) -> int:
265+
"""The magnetic field range.
266+
267+
Options are:
268+
- RANGE_30G (0x00): ±30 Gauss range
269+
- RANGE_12G (0x01): ±12 Gauss range
270+
- RANGE_8G (0x02): ±8 Gauss range
271+
- RANGE_2G (0x03): ±2 Gauss range
272+
"""
273+
return self._range
274+
275+
@range.setter
276+
def range(self, value: int) -> None:
277+
if value not in {RANGE_30G, RANGE_12G, RANGE_8G, RANGE_2G}:
278+
raise ValueError("Invalid range")
279+
self._range = value
280+
281+
@property
282+
def setreset_mode(self) -> int:
283+
"""The set/reset mode.
284+
285+
Options are:
286+
- SETRESET_ON (0x00): Set and reset on
287+
- SETRESET_SETONLY (0x01): Set only on
288+
- SETRESET_OFF (0x02): Set and reset off
289+
"""
290+
return self._setreset
291+
292+
@setreset_mode.setter
293+
def setreset_mode(self, value: int) -> None:
294+
if value not in {SETRESET_ON, SETRESET_SETONLY, SETRESET_OFF}:
295+
raise ValueError("Invalid set/reset mode")
296+
self._setreset = value
297+
298+
def soft_reset(self) -> None:
299+
"""Perform a soft reset of the chip."""
300+
self._reset = True
301+
time.sleep(0.05) # Wait 50ms for reset to complete
302+
303+
# Verify chip ID after reset
304+
if self._chip_id != 0x80:
305+
raise RuntimeError("Chip ID invalid after reset")
306+
307+
def self_test(self) -> bool:
308+
"""Perform self-test of the chip.
309+
310+
:return: True if self-test passed, False otherwise
311+
"""
312+
self._selftest = True
313+
time.sleep(0.005) # Wait 5ms for self-test to complete
314+
315+
# Check if self-test bit auto-cleared (indicates completion)
316+
return not self._selftest

docs/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
# Uncomment the below if you use native CircuitPython modules such as
2626
# digitalio, micropython and busio. List the modules you use. Without it, the
2727
# autodoc module docs will fail to generate with a warning.
28-
# autodoc_mock_imports = ["digitalio", "busio"]
28+
autodoc_mock_imports = ["digitalio", "busio"]
2929

3030
autodoc_preserve_defaults = True
3131

docs/index.rst

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,12 @@ Table of Contents
2424
.. toctree::
2525
:caption: Tutorials
2626

27-
.. todo:: Add any Learn guide links here. If there are none, then simply delete this todo and leave
28-
the toctree above for use later.
27+
Adafruit QMC5883P - Triple Axis Magnetometer Learn Guide <https://learn.adafruit.com/adafruit-qmc5883p-triple-axis-magnetometer>
2928

3029
.. toctree::
3130
:caption: Related Products
3231

33-
.. todo:: Add any product links here. If there are none, then simply delete this todo and leave
34-
the toctree above for use later.
32+
Adafruit QMC5883P - Triple Axis Magnetometer - STEMMA QT <https://www.adafruit.com/product/6388>
3533

3634
.. toctree::
3735
:caption: Other Links

0 commit comments

Comments
 (0)