Mobile Movement Data

The Bluefruit Connect app allows you to access the accelerometer, magnetometer, gyroscopic and quaternion movement information from your mobile device. This demo will show you how to access that data and print it to the serial console.

Save the following as code.py on your CIRCUITPY drive and then connect to the board using the Bluefruit LE Connect app. Then, connect to the serial console.

from adafruit_ble.uart import UARTServer
from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.accelerometer_packet import AccelerometerPacket
from adafruit_bluefruit_connect.magnetometer_packet import MagnetometerPacket
from adafruit_bluefruit_connect.gyro_packet import GyroPacket
from adafruit_bluefruit_connect.quaternion_packet import QuaternionPacket


uart_server = UARTServer()

while True:
    uart_server.start_advertising()
    while not uart_server.connected:
        pass

    # Now we're connected

    while uart_server.connected:
        if uart_server.in_waiting:
            packet = Packet.from_stream(uart_server)
            if isinstance(packet, AccelerometerPacket):
                print("Acceleration:", packet.x, packet.y, packet.z)
            if isinstance(packet, MagnetometerPacket):
                print("Magnetometer:", packet.x, packet.y, packet.z)
            if isinstance(packet, GyroPacket):
                print("Gyro:", packet.x, packet.y, packet.z)
            if isinstance(packet, QuaternionPacket):
                print("Quaternion:", packet.x, packet.y, packet.z)

    # If we got here, we lost the connection. Go up to the top and start
    # advertising again and waiting for a connection.

Connect to your board using the Bluefruit LE Connect application and navigate to the controller page. Enable the following streams: Quaternion, Accelerometer, Gyro, Magnetometer.

Let's take a look at the code.

First we import the necessary libraries and instantiate the UART server.

Inside the loop, we first begin advertising.

Once connected, the board begins listening for packets. In the event that an accelerometer, magnetometer, gyro or quaternion packet is received, it prints a message to the serial console.

That's all there is to accessing acceleration, magnetometer, gyro and quaternion data from your mobile using the Bluefruit LE Connect app and CircuitPython!

This guide was first published on Feb 25, 2019. It was last updated on Feb 25, 2019. This page (Mobile Movement Data) was last updated on Oct 16, 2019.