click the alien

Real-time plotting of android accelerometer data

What is a accelerometer?

It's a device aimed to measure acceleration. Usually it works analyzing the gravity force against a suspended mass. Or in the case of our smartphone, it analyze what is called seismic mass. Further explanation about accelerometers can be get here and here.

What are the uses of a accelerometer?

In smartphones, the most common use is to set the screen orientation or to achieve movimentation in games. Outside the phone world, it's widely used in stabilization systems.

What I'm trying to accomplish?

The idea is to plot the accelerometer data from a smartphone(android) using python. When you run the code, you should see something like this at your computer:

Accelerometer chart

The code

import android
import time
import matplotlib.pyplot as plt

class Chart(object):

    def __init__(self):
        self.senses = 0
        self.sb, self.xbuf, self.ybuf, self.zbuf = 0, 0, 0, 0
        plt.ion()
        self.fig = plt.figure(1, figsize=(19, 6))
        plt.ylim([-20, 20])
        plt.xlim([0, 300])

    def plot(self, x, y, z):
        self.senses += 1
        plt.plot([self.sb, self.senses], [self.xbuf, x], color='r', label='X')
        plt.plot([self.sb, self.senses], [self.ybuf, y], color='g', label='Y')
        plt.plot([self.sb, self.senses], [self.zbuf, z], color='b', label='Z')
        self.fig.canvas.draw()
        self.sb, self.xbuf, self.ybuf, self.zbuf = self.senses, x, y, z

# Interval between sensing
dt = 100

# Number of senses
TotalToSense = 250

# Connect to android and start sensing
android_address = ("192.168.0.1", 9999)
droid = android.Android(android_address)
droid.startSensingTimed(2, dt)

if __name__ == "__main__":
    amountSensed = 0
    chart = Chart()
    while amountSensed <= TotalToSense:
        x, y, z = droid.sensorsReadAccelerometer().result
        if x and y and z:
            x, y, z = round(x, 1), round(y, 1), round(z, 1)
            chart.plot(x, y, z)
            time.sleep(dt / 1000.0)
            amountSensed += 1
    droid.stopSensing()

The explanation

class Chart().__init__()

1) Start the count/buffers variables; 2) plt.ion() enables interactive mode, which will allow the plot to be updated in real time; 3) Create the chart figure, and define the scale of axis Y/X;

class Chart().plot()

1) Plot the data from accelerometer; 2) Draw the chart; 3) Update the buffers;

if _name_ == __main__

1) receive data from android accelerometer; 2) round to just one decimal; 3) call the plotting stuff 4) delay before the next sensing;

Considerations


Ricardo Pascal wrote this on Oct 25, 2012