Visualize accelerometer information from the microcomputer board in real time with mbed + Python

I used the NXP FRDM-KL25Z board. Since the 3-axis accelerometer MMA8451Q was listed, I took up the information by serial communication from here and plotted it in real time with Python. Saw.

(Accelerometer) FRDM-KL25Z --- (Serial) ---> PC (Real-time plot)

FRDM-KL25Z has the configuration shown below.

FRDM-KL25Z-1 2.jpg

Farm development on the microcomputer board side

I used mbed. Now, in order to include the MMA8451Q.h file, go to here to add the MMA8451Q library to the mbed compiler. To import.

accel_serial.cpp


#include "mbed.h"
#include "MMA8451Q.h"
 
#define MMA8451_I2C_ADDRESS (0x1d<<1)
 
DigitalOut myled(LED_GREEN);
Serial pc(USBTX, USBRX);
MMA8451Q acc(PTE25, PTE24, MMA8451_I2C_ADDRESS);
PwmOut rled(LED_RED);
PwmOut gled(LED_GREEN);
PwmOut bled(LED_BLUE);
    
int main()
{
    pc.printf("Hello World!\n");

    while (true) {
        pc.printf("%f,", acc.getAccX());
        pc.printf("%f,", acc.getAccY());
        pc.printf("%f\n", acc.getAccZ());
        rled = 1.0 - abs(acc.getAccX());
        gled = 1.0 - abs(acc.getAccY());
        bled = 1.0 - abs(acc.getAccZ());
        wait(0.2);
    }
}

After writing the program, I compiled it, downloaded the binary file, and dragged and dropped the FRDM-KL25Z to the folder recognized by USB.

Visualization application development on the PC side

I used Python. Install the library with pip

$ pip install numpy matplotlib seaborn pyserial

Next, connect FRDM-KL25Z via USB and check the allocation destination.

$ ls /dev/tty*

In my environment it was assigned to / dev / ttyACM1. If they are different, rewrite the / dev / ttyACM1 part in the program. Create the following python file and execute it to complete. (Please execute with sudo authority) When you tilt the FRDM-KL25Z, the acceleration information will be reflected in the graph.

plot_accel.py


from __future__ import unicode_literals, print_function
import numpy as np
import matplotlib.pyplot as plt
import serial
import seaborn as sns
sns.set(font_scale=2)
s = serial.Serial('/dev/ttyACM1')

fig, ax = plt.subplots(3, 1)

t = np.arange(0,10,0.1)
list_x = np.zeros(100).tolist()
list_y = np.zeros(100).tolist()
list_z = np.zeros(100).tolist()

lines_x, = ax[0].plot(t, list_x)
lines_y, = ax[1].plot(t, list_y)
lines_z, = ax[2].plot(t, list_z)

ax[0].set_ylim((-90,90))
ax[1].set_ylim((-90,90))
ax[2].set_ylim((-1,1))
ax[0].set_ylabel("Rot_X", size=30)
ax[1].set_ylabel("Rot_Y", size=30)
ax[2].set_ylabel("Z", size=30)

acc = s.readline().split(",") # just for warming up

while True:
    t += 0.1
    acc = s.readline().split(",")
    acc_x = float(acc[0])*90
    acc_y = float(acc[1])*90
    acc_z = float(acc[2])

    list_x.pop(0)
    list_x.append(acc_x)
    list_y.pop(0)
    list_y.append(acc_y)
    list_z.pop(0)
    list_z.append(acc_z)

    plt.draw()

    lines_x.set_data(t, list_x)
    lines_y.set_data(t, list_y)
    lines_z.set_data(t, list_z)
    ax[0].set_xlim((t.min(), t.max()))
    ax[1].set_xlim((t.min(), t.max()))
    ax[2].set_xlim((t.min(), t.max()))

    plt.pause(.0001)

Supplementary comment

Getting the serial signal is the following part:

s = serial.Serial('/dev/ttyACM1')
acc = s.readline().split(",")

Real-time plot updates could be achieved by using the following instead of plt.show ().

plt.draw()

# ... matplotlib.Update lines element...

plt.pause(.0001)

Reference: http://qiita.com/hausen6/items/b1b54f7325745ae43e47

Recommended Posts

Visualize accelerometer information from the microcomputer board in real time with mbed + Python
Output the time from the time the program was started in python
Get standard output in real time with Python subprocess
I tried to describe the traffic in real time with WebSocket
Read a file in Python with a relative path from the program
Visualize the frequency of word occurrences in sentences with Word Cloud. [Python]
Collecting information from Twitter with Python (Twitter API)
Fill the string with zeros in python and count some characters from the string
How to get the date and time difference in seconds with python
Display Python 3 in the browser with MAMP
MongoDB for the first time in Python
Get and convert the current time in the system local timezone with python
Make the library created by Eigen in C ++ available from Python with Boost.Numpy.
What I did when I got stuck in the time limit with lambda python
Pulling songwriting, composition and arrangement information from the Tower Records site with Python
Get information on the 100 most influential tech Twitter users in the world with python.
Location information data display in Python --Try plotting with the map display library (folium)-
Turn multiple lists with a for statement at the same time in Python
Get time series data from k-db.com in Python
Collecting information from Twitter with Python (Environment construction)
[Python] Get the files in a folder with Python
Load the network modeled with Rhinoceros in Python ③
[Automation] Extract the table in PDF with Python
Use logger with Python for the time being
Read the output of subprocess.Popen in real time
Load the network modeled with Rhinoceros in Python ②
Get BTC / JPY board information from Python --bitflyer
Try converting videos in real time with OpenCV
Load the network modeled with Rhinoceros in Python ①
Microcomputer with Python
Get the value of a specific key in a list from the dictionary type in the list with Python
Obtain location information (latitude and longitude) from the address. Geocode in Python ~ Geocoder and pydams ~
Basic information Write the 2018 fall algorithm problem in Python
Change the time zone with Docker in Oracle Database
Learn Nim with Python (from the beginning of the year).
Convert date timezone (time difference) in Python (from string)
Run with CentOS7 + Apache2.4 + Python3.6 for the time being
[Python] Get the numbers in the graph image with OCR
Collecting information from Twitter with Python (morphological analysis with MeCab)
Visualize the range of interpolation and extrapolation with python
Crawl the URL contained in the twitter tweet with python
Convert the image in .zip to PDF with Python
Get the result in dict format with Python psycopg2
Write letters in the card illustration with OpenCV python
Information for controlling the motor with Python on RaspberryPi
Find the part that is 575 from Wikipedia in Python
Install the latest Python from pyenv installed with homebrew
Extract the band information of raster data with python
How to write offline real time I tried to solve the problem of F02 with Python
Put Ubuntu in Raspi, put Docker on it, and control GPIO with python from the container
Try scraping the data of COVID-19 in Tokyo with Python
Try converting webcam / camcorder videos in real time with OpenCV
I tried using the Python library from Ruby with PyCall
Get your heart rate from the fitbit API in Python!
Visualize the results of decision trees performed with Python scikit-learn
Reinforcement learning in the shortest time with Keras with OpenAI Gym
Calculate the square root of 2 in millions of digits with python
[Understand in the shortest time] Python basics for data analysis
Get the value while specifying the default value from dict in Python
[Homology] Count the number of holes in data with Python
[Python] Display the elapsed time in hours, minutes, and seconds (00:00:00)