Simple test¶
Ensure your device works with this simple test.
1# SPDX-FileCopyrightText: 2018 Tony DiCola for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4# Simple demo of reading the MMA8451 orientation every second.
5
6import time
7import board
8import adafruit_mma8451
9
10
11# Create sensor object, communicating over the board's default I2C bus
12i2c = board.I2C() # uses board.SCL and board.SDA
13# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
14
15# Initialize MMA8451 module.
16sensor = adafruit_mma8451.MMA8451(i2c)
17# Optionally change the address if it's not the default:
18# sensor = adafruit_mma8451.MMA8451(i2c, address=0x1C)
19
20# Optionally change the range from its default of +/-4G:
21# sensor.range = adafruit_mma8451.RANGE_2G # +/- 2G
22# sensor.range = adafruit_mma8451.RANGE_4G # +/- 4G (default)
23# sensor.range = adafruit_mma8451.RANGE_8G # +/- 8G
24
25# Optionally change the data rate from its default of 800hz:
26# sensor.data_rate = adafruit_mma8451.DATARATE_800HZ # 800Hz (default)
27# sensor.data_rate = adafruit_mma8451.DATARATE_400HZ # 400Hz
28# sensor.data_rate = adafruit_mma8451.DATARATE_200HZ # 200Hz
29# sensor.data_rate = adafruit_mma8451.DATARATE_100HZ # 100Hz
30# sensor.data_rate = adafruit_mma8451.DATARATE_50HZ # 50Hz
31# sensor.data_rate = adafruit_mma8451.DATARATE_12_5HZ # 12.5Hz
32# sensor.data_rate = adafruit_mma8451.DATARATE_6_25HZ # 6.25Hz
33# sensor.data_rate = adafruit_mma8451.DATARATE_1_56HZ # 1.56Hz
34
35# Main loop to print the acceleration and orientation every second.
36while True:
37 x, y, z = sensor.acceleration
38 print(
39 "Acceleration: x={0:0.3f}m/s^2 y={1:0.3f}m/s^2 z={2:0.3f}m/s^2".format(x, y, z)
40 )
41 orientation = sensor.orientation
42 # Orientation is one of these values:
43 # - PL_PUF: Portrait, up, front
44 # - PL_PUB: Portrait, up, back
45 # - PL_PDF: Portrait, down, front
46 # - PL_PDB: Portrait, down, back
47 # - PL_LRF: Landscape, right, front
48 # - PL_LRB: Landscape, right, back
49 # - PL_LLF: Landscape, left, front
50 # - PL_LLB: Landscape, left, back
51 print("Orientation: ", end="")
52 if orientation == adafruit_mma8451.PL_PUF:
53 print("Portrait, up, front")
54 elif orientation == adafruit_mma8451.PL_PUB:
55 print("Portrait, up, back")
56 elif orientation == adafruit_mma8451.PL_PDF:
57 print("Portrait, down, front")
58 elif orientation == adafruit_mma8451.PL_PDB:
59 print("Portrait, down, back")
60 elif orientation == adafruit_mma8451.PL_LRF:
61 print("Landscape, right, front")
62 elif orientation == adafruit_mma8451.PL_LRB:
63 print("Landscape, right, back")
64 elif orientation == adafruit_mma8451.PL_LLF:
65 print("Landscape, left, front")
66 elif orientation == adafruit_mma8451.PL_LLB:
67 print("Landscape, left, back")
68 time.sleep(1.0)