-
Notifications
You must be signed in to change notification settings - Fork 16
/
adafruit_mma8451.py
266 lines (216 loc) · 8.97 KB
/
adafruit_mma8451.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# SPDX-FileCopyrightText: 2017 Tony DiCola for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_mma8451`
====================================================
CircuitPython module for the MMA8451 3 axis accelerometer. See
examples/simpletest.py for a demo of the usage.
* Author(s): Tony DiCola
Implementation Notes
--------------------
**Hardware:**
* Adafruit `Triple-Axis Accelerometer - ±2/4/8g @ 14-bit - MMA8451
<https://www.adafruit.com/product/2019>`_
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://circuitpython.org/downloads
* Adafruit's Bus Device library:
https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""
import struct
from micropython import const
from adafruit_bus_device import i2c_device
try:
from typing import Optional, Tuple
from busio import I2C
except ImportError:
pass
__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MMA8451.git"
# Internal constants:
_MMA8451_DEFAULT_ADDRESS = const(0x1D)
_MMA8451_REG_OUT_X_MSB = const(0x01)
_MMA8451_REG_SYSMOD = const(0x0B)
_MMA8451_REG_WHOAMI = const(0x0D)
_MMA8451_REG_XYZ_DATA_CFG = const(0x0E)
_MMA8451_REG_PL_STATUS = const(0x10)
_MMA8451_REG_PL_CFG = const(0x11)
_MMA8451_REG_CTRL_REG1 = const(0x2A)
_MMA8451_REG_CTRL_REG2 = const(0x2B)
_MMA8451_REG_CTRL_REG4 = const(0x2D)
_MMA8451_REG_CTRL_REG5 = const(0x2E)
_MMA8451_DATARATE_MASK = const(0b111)
_SENSORS_GRAVITY_EARTH = 9.80665
# External user-facing constants:
PL_PUF = 0 # Portrait, up, front
PL_PUB = 1 # Portrait, up, back
PL_PDF = 2 # Portrait, down, front
PL_PDB = 3 # Portrait, down, back
PL_LRF = 4 # Landscape, right, front
PL_LRB = 5 # Landscape, right, back
PL_LLF = 6 # Landscape, left, front
PL_LLB = 7 # Landscape, left, back
RANGE_8G = 0b10 # +/- 8g
RANGE_4G = 0b01 # +/- 4g (default value)
RANGE_2G = 0b00 # +/- 2g
DATARATE_800HZ = 0b000 # 800Hz
DATARATE_400HZ = 0b001 # 400Hz
DATARATE_200HZ = 0b010 # 200Hz
DATARATE_100HZ = 0b011 # 100Hz
DATARATE_50HZ = 0b100 # 50Hz
DATARATE_12_5HZ = 0b101 # 12.5Hz
DATARATE_6_25HZ = 0b110 # 6.25Hz
DATARATE_1_56HZ = 0b111 # 1.56Hz
class MMA8451:
"""MMA8451 accelerometer. Create an instance by specifying:
:param ~busio.I2C i2c: The I2C bus the device is connected to.
:param int address: The I2C device address. Defaults to :const:`0x1D`
**Quickstart: Importing and using the device**
Here is an example of using the :class:`MMA8451` class.
First you will need to import the libraries to use the sensor
.. code-block:: python
import board
import adafruit_mma8451
Once this is done you can define your `board.I2C` object and define your sensor object
.. code-block:: python
i2c = board.I2C() # uses board.SCL and board.SDA
sensor = adafruit_mma8451.MMA8451(i2c)
Now you have access to the :attr:`acceleration` and :attr:`orientation` attributes
.. code-block:: python
acc_x, acc_y, acc_z = sensor.acceleration
orientation = sensor.orientation
"""
# Class-level buffer to reduce allocations and fragmentation.
# Note this is NOT thread-safe or re-entrant by design!
_BUFFER = bytearray(6)
def __init__(self, i2c: I2C, *, address: int = _MMA8451_DEFAULT_ADDRESS) -> None:
self._device = i2c_device.I2CDevice(i2c, address)
# Verify device ID.
if self._read_u8(_MMA8451_REG_WHOAMI) != 0x1A:
raise RuntimeError("Failed to find MMA8451, check wiring!")
# Reset and wait for chip to be ready.
self._write_u8(_MMA8451_REG_CTRL_REG2, 0x40)
while self._read_u8(_MMA8451_REG_CTRL_REG2) & 0x40 > 0:
pass
# Enable 4G range.
self._write_u8(_MMA8451_REG_XYZ_DATA_CFG, RANGE_4G)
# High resolution mode.
self._write_u8(_MMA8451_REG_CTRL_REG2, 0x02)
# DRDY on INT1
self._write_u8(_MMA8451_REG_CTRL_REG4, 0x01)
self._write_u8(_MMA8451_REG_CTRL_REG5, 0x01)
# Turn on orientation config
self._write_u8(_MMA8451_REG_PL_CFG, 0x40)
# Activate at max rate, low noise mode
self._write_u8(_MMA8451_REG_CTRL_REG1, 0x01 | 0x04)
def _read_into(
self, address: int, buf: bytearray, count: Optional[int] = None
) -> bytearray:
# Read bytes from the specified address into the provided buffer.
# If count is not specified (the default) the entire buffer is filled,
# otherwise only count bytes are copied in.
# It's silly that pylint complains about an explicit check that buf
# has at least 1 value. I don't trust the implicit true/false
# recommendation as it was not designed for bytearrays which may not
# follow that semantic. Ignore pylint's superfulous complaint.
assert len(buf) > 0 # pylint: disable=len-as-condition
if count is None:
count = len(buf)
with self._device as i2c:
i2c.write_then_readinto(bytes([address & 0xFF]), buf, in_end=count)
def _read_u8(self, address: int) -> int:
# Read an 8-bit unsigned value from the specified 8-bit address.
self._read_into(address, self._BUFFER, count=1)
return self._BUFFER[0]
def _write_u8(self, address: int, val: int) -> None:
# Write an 8-bit unsigned value to the specified 8-bit address.
with self._device as i2c:
self._BUFFER[0] = address & 0xFF
self._BUFFER[1] = val & 0xFF
i2c.write(self._BUFFER, end=2)
@property
def range(self) -> int:
"""Get and set the range of the sensor. Must be a value of:
* ``RANGE_8G``: +/- 8g
* ``RANGE_4G``: +/- 4g (the default)
* ``RANGE_2G``: +/- 2g
"""
return self._read_u8(_MMA8451_REG_XYZ_DATA_CFG) & 0x03
@range.setter
def range(self, val: int) -> None:
assert 0 <= val <= 2
reg1 = self._read_u8(_MMA8451_REG_CTRL_REG1)
self._write_u8(_MMA8451_REG_CTRL_REG1, 0x00) # deactivate
self._write_u8(_MMA8451_REG_XYZ_DATA_CFG, val)
self._write_u8(_MMA8451_REG_CTRL_REG1, reg1 | 0x01) # activate
@property
def data_rate(self) -> int:
"""Get and set the data rate of the sensor. Must be a value of:
* ``DATARATE_800HZ``: 800Hz (the default)
* ``DATARATE_400HZ``: 400Hz
* ``DATARATE_200HZ``: 200Hz
* ``DATARATE_100HZ``: 100Hz
* ``DATARATE_50HZ``: 50Hz
* ``DATARATE_12_5HZ``: 12.5Hz
* ``DATARATE_6_25HZ``: 6.25Hz
* ``DATARATE_1_56HZ``: 1.56Hz
"""
return (self._read_u8(_MMA8451_REG_CTRL_REG1) >> 3) & _MMA8451_DATARATE_MASK
@data_rate.setter
def data_rate(self, val: int) -> None:
assert 0 <= val <= 7
ctl1 = self._read_u8(_MMA8451_REG_CTRL_REG1)
self._write_u8(_MMA8451_REG_CTRL_REG1, 0x00) # deactivate
ctl1 &= ~(_MMA8451_DATARATE_MASK << 3) # mask off bits
ctl1 |= val << 3
self._write_u8(_MMA8451_REG_CTRL_REG1, ctl1 | 0x01) # activate
@property
def acceleration(self) -> Tuple[float, float, float]:
# pylint: disable=no-else-return
# This needs to be refactored when it can be tested
"""Get the acceleration measured by the sensor. Will return a 3-tuple
of X, Y, Z axis acceleration values in :math:`m/s^2`.
"""
# Read 6 bytes for 16-bit X, Y, Z values.
self._read_into(_MMA8451_REG_OUT_X_MSB, self._BUFFER, count=6)
# Reconstruct signed 16-bit integers.
x, y, z = struct.unpack(">hhh", self._BUFFER)
x >>= 2
y >>= 2
z >>= 2
# Scale values based on current sensor range to get proper units.
_range = self.range
if _range == RANGE_8G:
return (
x / 1024.0 * _SENSORS_GRAVITY_EARTH,
y / 1024.0 * _SENSORS_GRAVITY_EARTH,
z / 1024.0 * _SENSORS_GRAVITY_EARTH,
)
elif _range == RANGE_4G:
return (
x / 2048.0 * _SENSORS_GRAVITY_EARTH,
y / 2048.0 * _SENSORS_GRAVITY_EARTH,
z / 2048.0 * _SENSORS_GRAVITY_EARTH,
)
elif _range == RANGE_2G:
return (
x / 4096.0 * _SENSORS_GRAVITY_EARTH,
y / 4096.0 * _SENSORS_GRAVITY_EARTH,
z / 4096.0 * _SENSORS_GRAVITY_EARTH,
)
else:
raise RuntimeError("Unexpected range!")
@property
def orientation(self) -> int:
"""Get the orientation of the MMA8451. Will return a value of:
* ``PL_PUF``: Portrait, up, front
* ``PL_PUB``: Portrait, up, back
* ``PL_PDF``: Portrait, down, front
* ``PL_PDB``: Portrait, down, back
* ``PL_LRF``: Landscape, right, front
* ``PL_LRB``: Landscape, right, back
* ``PL_LLF``: Landscape, left, front
* ``PL_LLB``: Landscape, left, back
"""
return self._read_u8(_MMA8451_REG_PL_STATUS) & 0x07