Accelerometer module

The PyMetaWear implementation of the libmetawear accelerometer module.

It is initialized at the creation of the MetaWearClient client and can then be accessed in the accelerometer attribute of the client.

Data streaming example

If you need a real time stream of sensor data, use the notifications() method on the accelerometer module:

from pymetawear.client import MetaWearClient

c = MetaWearClient('DD:3A:7D:4D:56:F0')

# Set data rate to 200 Hz and measuring range to +/- 8g
c.accelerometer.set_settings(data_rate=200.0, data_range=8)

def acc_callback(data):
    """Handle a (epoch, (x,y,z)) accelerometer tuple."""
    print("Epoch time: [{0}] - X: {1}, Y: {2}, Z: {3}".format(data[0], *data[1]))

# Enable notifications and register a callback for them.
c.accelerometer.notifications(acc_callback)

Logging example

If you want to log data to the MetaWear board and retrieve it after some time, then use the start_logging(), stop_logging() and download_log() methods:

import os
import json
import time

from pymetawear.client import MetaWearClient
from pymetawear.exceptions import PyMetaWearException, PyMetaWearDownloadTimeout

c = MetaWearClient('DD:3A:7D:4D:56:F0')

# Set data rate to 200 Hz and measuring range to +/- 8g
c.accelerometer.set_settings(data_rate=200.0, data_range=8)

# Log data for 10 seconds.
c.accelerometer.start_logging()
print("Logging accelerometer data...")

time.sleep(10.0)

c.accelerometer.stop_logging()
print("Finished logging.")

# Download the stored data from the MetaWear board.
print("Downloading data...")
download_done = False
n = 0
data = None
while (not download_done) and n < 3:
    try:
        data = c.accelerometer.download_log()
        download_done = True
    except PyMetaWearDownloadTimeout:
        print("Download of log interrupted. Trying to reconnect...")
        c.disconnect()
        c.connect()
        n += 1
if data is None:
    raise PyMetaWearException("Download of logging data failed.")

print("Disconnecting...")
c.disconnect()

# Save the logged data.
class MetaWearDataEncoder(json.JSONEncoder):
    """JSON Encoder for converting ``mbientlab`` module's CartesianFloat
    class to data tuple ``(x,y,z)``."""
    def default(self, o):
        if isinstance(o, CartesianFloat):
            return o.x, o.y, o.z
        else:
            return super(MetaWearDataEncoder, self).default(o)

data_file = os.path.join(os.getcwd(), "logged_data.json")
print("Saving the data to file: {0}".format(data_file))
with open("logged_data.json", "wt") as f:
    json.dump(data, f, indent=2)

API

Accelerometer module

Created by hbldh <henrik.blidh@nedomkull.com> on 2016-04-14 Modified by lkasso <hello@mbientlab.com>

class pymetawear.modules.accelerometer.AccelerometerModule(board, module_id)[source]

MetaWear accelerometer module implementation.

Parameters:
  • board (ctypes.c_long) – The MetaWear board pointer value.
  • module_id (int) – The module id of this accelerometer component, obtained from libmetawear.
  • debug (bool) – If True, module prints out debug information.
data_signal

Returns the data signal pointer value for the switch module.

Returns:The pointer value. (Long if on x64 architecture.)
Return type:ctypes.c_long or ctypes.c_int
module_name

Get module name.

Returns:The name of this module.
Return type:str
notifications(callback=None)[source]

Subscribe or unsubscribe to accelerometer notifications.

Convenience method for handling accelerometer usage.

Example:

def handle_acc_notification(data)
    # Handle dictionary with [epoch, value] keys.
    epoch = data["epoch"]
    xyz = data["value"]
    print(str(data))

mwclient.accelerometer.notifications(handle_acc_notification)
Parameters:callback (callable) – Accelerometer notification callback function. If None, unsubscription to accelerometer notifications is registered.
sensor_name

Get sensor name, if applicable.

Returns:The name of this module.
Return type:str or None
set_settings(data_rate=None, data_range=None)[source]

Set accelerometer settings.

Can be called with two or only one setting:

mwclient.set_accelerometer_settings(data_rate=200.0, data_range=8.0)

will give the same result as

mwclient.set_accelerometer_settings(data_rate=200.0)
mwclient.set_accelerometer_settings(data_range=8.0)

albeit that the latter example makes two writes to the board.

Call get_possible_settings() to see which values that can be set for this sensor.

Parameters:
  • data_rate (float) – The frequency of accelerometer updates in Hz.
  • data_range (float) – The measurement range in the unit g.
start()[source]

Switches the accelerometer to active mode.

stop()[source]

Switches the accelerometer to standby mode.

toggle_sampling(enabled=True)[source]

Enables or disables accelerometer sampling.

Parameters:enabled (bool) – Desired state of the accelerometer.