Friday, December 12, 2014

58. Exploring the Pi B+'s Ports IV - Reading the MPU-6050 using Python

26,000 page views!!
The last post described the 3D wireframe demonstration of the MPU-6050's rotations (ie the GY-521 breakout board) about the x-, y- and z-axes, and other scripts which displayed the readout of quaternions etc.  Those test programs were written in the C++ programming language. 

This time test programs are written in Python, giving me a better chance of understanding what's going on!  The circuitry is identical to that used in the last post, and of course, the I2C interface has previously been enabled.

smbus is a Python module which allows SMBus (system management bus - a sub-set of the I2C protocol) access through the I2C interface on Linux hosts. This is the key module for Python access.

Reading Accelerometer Data


In this first program, in addition to reading the data from the accelerometer, the output values are sent to a web page, just for fun!  The address of the web page depends on the Pi's IP address, which can be found using the terminal command

ifconfig

and appending :8080 to the end.   For example,

http://ip-address-of-your-pi:8080

Here's the Python code for server.py:

Andrew Birkett's really neat code reads the accelerometer part of the MPU-6050 and prints out the x- and y-axis rotations which are calculated by the program.  The output via the web page looks like this:
x-rotation: 0.2 degrees.   y-rotation: -2.2 degrees.

The values of course change as the MPU-6050 is rotated about its x- and y-axes. for example:
x-rotation: 50.8 degrees.   y-rotation: 18.4 degrees.
The web page has to be refreshed to see new values.

Reading Gyro & Accelerometer Data

This program, Reading6050.py, also written by Andrew Birkett, looks like this:

The program produces results like this:
pi@raspberrypi ~ $ sudo python Reading6050.py
gyro data
---------
gyro_xout:  -202  scaled:  -2
gyro_yout:  -191  scaled:  -2
gyro_zout:  11  scaled:  0

accelerometer data
------------------
accel_xout:  176  scaled:  0.0107421875
accel_yout:  160  scaled:  0.009765625
accel_zout:  15364  scaled:  0.937744140625
x rotation:  0.596614942501
y rotation:  -0.656278927449
pi@raspberrypi ~ $ 
So what does the program do and what do these results mean?

No comments:

Post a Comment