Skip to content

Commit f082793

Browse files
iabdalkaderdpgeorge
authored andcommitted
drivers/lsm6dsox: Add LSM6DSOX driver and examples.
1 parent 3745c39 commit f082793

File tree

3 files changed

+295
-0
lines changed

3 files changed

+295
-0
lines changed

drivers/lsm6dsox/lsm6dsox.py

Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
"""
2+
LSM6DSOX STMicro driver for MicroPython based on LSM9DS1:
3+
Source repo: https://github.com/hoihu/projects/tree/master/raspi-hat
4+
5+
The MIT License (MIT)
6+
7+
Copyright (c) 2021 Damien P. George
8+
Copyright (c) 2021 Ibrahim Abdelkader <[email protected]>
9+
10+
Permission is hereby granted, free of charge, to any person obtaining a copy
11+
of this software and associated documentation files (the "Software"), to deal
12+
in the Software without restriction, including without limitation the rights
13+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14+
copies of the Software, and to permit persons to whom the Software is
15+
furnished to do so, subject to the following conditions:
16+
17+
The above copyright notice and this permission notice shall be included in
18+
all copies or substantial portions of the Software.
19+
20+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26+
THE SOFTWARE.
27+
28+
Basic example usage:
29+
30+
import time
31+
from lsm6dsox import LSM6DSOX
32+
33+
from machine import Pin, I2C
34+
lsm = LSM6DSOX(I2C(0, scl=Pin(13), sda=Pin(12)))
35+
36+
while (True):
37+
print('Accelerometer: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_accel()))
38+
print('Gyroscope: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}'.format(*lsm.read_gyro()))
39+
print("")
40+
time.sleep_ms(100)
41+
"""
42+
import array
43+
from micropython import const
44+
45+
46+
class LSM6DSOX:
47+
_CTRL3_C = const(0x12)
48+
_CTRL1_XL = const(0x10)
49+
_CTRL8_XL = const(0x17)
50+
_CTRL9_XL = const(0x18)
51+
52+
_CTRL2_G = const(0x11)
53+
_CTRL7_G = const(0x16)
54+
55+
_OUTX_L_G = const(0x22)
56+
_OUTX_L_XL = const(0x28)
57+
_MLC_STATUS = const(0x38)
58+
59+
_DEFAULT_ADDR = const(0x6A)
60+
_WHO_AM_I_REG = const(0x0F)
61+
62+
_FUNC_CFG_ACCESS = const(0x01)
63+
_FUNC_CFG_BANK_USER = const(0)
64+
_FUNC_CFG_BANK_HUB = const(1)
65+
_FUNC_CFG_BANK_EMBED = const(2)
66+
67+
_MLC0_SRC = const(0x70)
68+
_MLC_INT1 = const(0x0D)
69+
_TAP_CFG0 = const(0x56)
70+
71+
_EMB_FUNC_EN_A = const(0x04)
72+
_EMB_FUNC_EN_B = const(0x05)
73+
74+
def __init__(
75+
self,
76+
i2c,
77+
address=_DEFAULT_ADDR,
78+
gyro_odr=104,
79+
accel_odr=104,
80+
gyro_scale=2000,
81+
accel_scale=4,
82+
ucf=None,
83+
):
84+
"""Initalizes Gyro and Accelerator.
85+
accel_odr: (0, 1.6Hz, 3.33Hz, 6.66Hz, 12.5Hz, 26Hz, 52Hz, 104Hz, 208Hz, 416Hz, 888Hz)
86+
gyro_odr: (0, 1.6Hz, 3.33Hz, 6.66Hz, 12.5Hz, 26Hz, 52Hz, 104Hz, 208Hz, 416Hz, 888Hz)
87+
gyro_scale: (245dps, 500dps, 1000dps, 2000dps)
88+
accel_scale: (+/-2g, +/-4g, +/-8g, +-16g)
89+
ucf: MLC program to load.
90+
"""
91+
self.i2c = i2c
92+
self.address = address
93+
94+
# check the id of the Accelerometer/Gyro
95+
if self.__read_reg(_WHO_AM_I_REG) != 108:
96+
raise OSError("No LSM6DS device was found at address 0x%x" % (self.address))
97+
98+
# allocate scratch buffer for efficient conversions and memread op's
99+
self.scratch_int = array.array("h", [0, 0, 0])
100+
101+
SCALE_GYRO = {250: 0, 500: 1, 1000: 2, 2000: 3}
102+
SCALE_ACCEL = {2: 0, 4: 2, 8: 3, 16: 1}
103+
# XL_HM_MODE = 0 by default. G_HM_MODE = 0 by default.
104+
ODR = {
105+
0: 0x00,
106+
1.6: 0x08,
107+
3.33: 0x09,
108+
6.66: 0x0A,
109+
12.5: 0x01,
110+
26: 0x02,
111+
52: 0x03,
112+
104: 0x04,
113+
208: 0x05,
114+
416: 0x06,
115+
888: 0x07,
116+
}
117+
118+
gyro_odr = round(gyro_odr, 2)
119+
accel_odr = round(accel_odr, 2)
120+
121+
# Sanity checks
122+
if not gyro_odr in ODR:
123+
raise ValueError("Invalid sampling rate: %d" % accel_odr)
124+
if not gyro_scale in SCALE_GYRO:
125+
raise ValueError("invalid gyro scaling: %d" % gyro_scale)
126+
if not accel_odr in ODR:
127+
raise ValueError("Invalid sampling rate: %d" % accel_odr)
128+
if not accel_scale in SCALE_ACCEL:
129+
raise ValueError("invalid accelerometer scaling: %d" % accel_scale)
130+
131+
# Soft-reset the device.
132+
self.reset()
133+
134+
# Load and configure MLC if UCF file is provided
135+
if ucf != None:
136+
self.load_mlc(ucf)
137+
138+
# Set Gyroscope datarate and scale.
139+
# Note output from LPF2 second filtering stage is selected. See Figure 18.
140+
self.__write_reg(_CTRL1_XL, (ODR[accel_odr] << 4) | (SCALE_ACCEL[accel_scale] << 2) | 2)
141+
142+
# Enable LPF2 and HPF fast-settling mode, ODR/4
143+
self.__write_reg(_CTRL8_XL, 0x09)
144+
145+
# Set Gyroscope datarate and scale.
146+
self.__write_reg(_CTRL2_G, (ODR[gyro_odr] << 4) | (SCALE_GYRO[gyro_scale] << 2) | 0)
147+
148+
self.gyro_scale = 32768 / gyro_scale
149+
self.accel_scale = 32768 / accel_scale
150+
151+
def __read_reg(self, reg, size=1):
152+
buf = self.i2c.readfrom_mem(self.address, reg, size)
153+
if size == 1:
154+
return int(buf[0])
155+
return [int(x) for x in buf]
156+
157+
def __write_reg(self, reg, val):
158+
self.i2c.writeto_mem(self.address, reg, bytes([val]))
159+
160+
def reset(self):
161+
self.__write_reg(_CTRL3_C, self.__read_reg(_CTRL3_C) | 0x1)
162+
for i in range(0, 10):
163+
if (self.__read_reg(_CTRL3_C) & 0x01) == 0:
164+
return
165+
time.sleep_ms(10)
166+
raise OSError("Failed to reset LSM6DS device.")
167+
168+
def set_mem_bank(self, bank):
169+
cfg = self.__read_reg(_FUNC_CFG_ACCESS) & 0x3F
170+
self.__write_reg(_FUNC_CFG_ACCESS, cfg | (bank << 6))
171+
172+
def set_embedded_functions(self, enable, emb_ab=None):
173+
self.set_mem_bank(_FUNC_CFG_BANK_EMBED)
174+
if enable:
175+
self.__write_reg(_EMB_FUNC_EN_A, emb_ab[0])
176+
self.__write_reg(_EMB_FUNC_EN_B, emb_ab[1])
177+
else:
178+
emb_a = self.__read_reg(_EMB_FUNC_EN_A)
179+
emb_b = self.__read_reg(_EMB_FUNC_EN_B)
180+
self.__write_reg(_EMB_FUNC_EN_A, (emb_a & 0xC7))
181+
self.__write_reg(_EMB_FUNC_EN_B, (emb_b & 0xE6))
182+
emb_ab = (emb_a, emb_b)
183+
184+
self.set_mem_bank(_FUNC_CFG_BANK_USER)
185+
return emb_ab
186+
187+
def load_mlc(self, ucf):
188+
# Load MLC config from file
189+
with open(ucf, "r") as ucf_file:
190+
for l in ucf_file:
191+
if l.startswith("Ac"):
192+
v = [int(v, 16) for v in l.strip().split(" ")[1:3]]
193+
self.__write_reg(v[0], v[1])
194+
195+
emb_ab = self.set_embedded_functions(False)
196+
197+
# Disable I3C interface
198+
self.__write_reg(_CTRL9_XL, self.__read_reg(_CTRL9_XL) | 0x01)
199+
200+
# Enable Block Data Update
201+
self.__write_reg(_CTRL3_C, self.__read_reg(_CTRL3_C) | 0x40)
202+
203+
# Route signals on interrupt pin 1
204+
self.set_mem_bank(_FUNC_CFG_BANK_EMBED)
205+
self.__write_reg(_MLC_INT1, self.__read_reg(_MLC_INT1) & 0x01)
206+
self.set_mem_bank(_FUNC_CFG_BANK_USER)
207+
208+
# Configure interrupt pin mode
209+
self.__write_reg(_TAP_CFG0, self.__read_reg(_TAP_CFG0) | 0x41)
210+
211+
self.set_embedded_functions(True, emb_ab)
212+
213+
def read_mlc_output(self):
214+
buf = None
215+
if self.__read_reg(_MLC_STATUS) & 0x1:
216+
self.__read_reg(0x1A, size=12)
217+
self.set_mem_bank(_FUNC_CFG_BANK_EMBED)
218+
buf = self.__read_reg(_MLC0_SRC, 8)
219+
self.set_mem_bank(_FUNC_CFG_BANK_USER)
220+
return buf
221+
222+
def read_gyro(self):
223+
"""Returns gyroscope vector in degrees/sec."""
224+
mv = memoryview(self.scratch_int)
225+
f = self.gyro_scale
226+
self.i2c.readfrom_mem_into(self.address, _OUTX_L_G, mv)
227+
return (mv[0] / f, mv[1] / f, mv[2] / f)
228+
229+
def read_accel(self):
230+
"""Returns acceleration vector in gravity units (9.81m/s^2)."""
231+
mv = memoryview(self.scratch_int)
232+
f = self.accel_scale
233+
self.i2c.readfrom_mem_into(self.address, _OUTX_L_XL, mv)
234+
return (mv[0] / f, mv[1] / f, mv[2] / f)

drivers/lsm6dsox/lsm6dsox_basic.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# LSM6DSOX Basic Example.
2+
import time
3+
from lsm6dsox import LSM6DSOX
4+
5+
from machine import Pin, I2C
6+
7+
lsm = LSM6DSOX(I2C(0, scl=Pin(13), sda=Pin(12)))
8+
9+
while True:
10+
print("Accelerometer: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}".format(*lsm.read_accel()))
11+
print("Gyroscope: x:{:>8.3f} y:{:>8.3f} z:{:>8.3f}".format(*lsm.read_gyro()))
12+
print("")
13+
time.sleep_ms(100)

drivers/lsm6dsox/lsm6dsox_mlc.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# LSM6DSOX IMU MLC (Machine Learning Core) Example.
2+
# Download the raw UCF file, copy to storage and reset.
3+
4+
# NOTE: The pre-trained models (UCF files) for the examples can be found here:
5+
# https://github.com/STMicroelectronics/STMems_Machine_Learning_Core/tree/master/application_examples/lsm6dsox
6+
7+
import time
8+
from lsm6dsox import LSM6DSOX
9+
from machine import Pin, I2C
10+
11+
INT_MODE = True # Run in interrupt mode.
12+
INT_FLAG = False # Set True on interrupt.
13+
14+
15+
def imu_int_handler(pin):
16+
global INT_FLAG
17+
INT_FLAG = True
18+
19+
20+
if INT_MODE == True:
21+
int_pin = Pin(24)
22+
int_pin.irq(handler=imu_int_handler, trigger=Pin.IRQ_RISING)
23+
24+
i2c = I2C(0, scl=Pin(13), sda=Pin(12))
25+
26+
# Vibration detection example
27+
UCF_FILE = "lsm6dsox_vibration_monitoring.ucf"
28+
UCF_LABELS = {0: "no vibration", 1: "low vibration", 2: "high vibration"}
29+
# NOTE: Selected data rate and scale must match the MLC data rate and scale.
30+
lsm = LSM6DSOX(i2c, gyro_odr=26, accel_odr=26, gyro_scale=2000, accel_scale=4, ucf=UCF_FILE)
31+
32+
# Head gestures example
33+
# UCF_FILE = "lsm6dsox_head_gestures.ucf"
34+
# UCF_LABELS = {0:"Nod", 1:"Shake", 2:"Stationary", 3:"Swing", 4:"Walk"}
35+
# NOTE: Selected data rate and scale must match the MLC data rate and scale.
36+
# lsm = LSM6DSOX(i2c, gyro_odr=26, accel_odr=26, gyro_scale=250, accel_scale=2, ucf=UCF_FILE)
37+
38+
print("MLC configured...")
39+
40+
while True:
41+
if INT_MODE:
42+
if INT_FLAG:
43+
INT_FLAG = False
44+
print(UCF_LABELS[lsm.read_mlc_output()[0]])
45+
else:
46+
buf = lsm.read_mlc_output()
47+
if buf != None:
48+
print(UCF_LABELS[buf[0]])

0 commit comments

Comments
 (0)