MPU-6050 sensor connected to Raspberry Pi

From BitWizard WIKI
Jump to: navigation, search

I was bored on a rainy sunday afternoon, so I connected an MPU-6050 6DOF (3 axis acceleromter, 3 axis gyroscope, thermometer) sensor to the I2C bus of my raspberry Pi. I also wrote some scripts to retrieve and parse the data. This is still a work in progress, but the basic features work.

The scripts

Download link for all the scripts: http://www.bitwizard.nl/software/mpu-6050-tools.tar.gz

Script to initialize the MPU-6050 (I named it mpu-6050-init):

#! /bin/sh

i2cset -y 0 0x68 0x6b 0

Script to read a byte (I named it mpu-6050-getbyte):

#! /bin/sh

ADDR=$1
i2cget -y 0 0x68 0x$ADDR | sed -e 's/^0x//g' | tr a-z A-Z

Script to read a word (I named it mpu-6050-getword):

#! /bin/sh

ADDR=`echo $1 | tr a-z A-Z`
ADDR2=`echo "ibase=16; obase=10; $ADDR+1" | bc`
VARmsb=`./mpu-6050-getbyte $ADDR;`
VARlsb=`./mpu-6050-getbyte $ADDR2;`
echo $VARmsb$VARlsb

Script to read the temperatue (I named it mpu-6050-gettemp):

#! /bin/sh

TEMP=`./mpu-6050-getword 41`
echo "ibase=16; scale=3; ((-((FFFF-$TEMP)+1))/154)+24.87" | bc

Script to read the accelerometers (I named it mpu-6050-getaccel):

#! /bin/sh

echo X: `./mpu-6050-getword 3B`
echo Y: `./mpu-6050-getword 3D`
echo Z: `./mpu-6050-getword 3F`

Script to read the gyroscopes (I named it mpu-6050-getgyro):

#! /bin/sh

echo X: `./mpu-6050-getword 43`
echo Y: `./mpu-6050-getword 45`
echo Z: `./mpu-6050-getword 47`

Script to read everything (I named it mpu-6050-getall):

#! /bin/sh

echo Accelerometer:
./mpu-6050-getaccel
echo
echo Gyroscope:
./mpu-6050-getgyro
echo
echo Temperature:
./mpu-6050-gettemp

PLEASE NOTE: These scripts are written on a version 1 board. To run them on a version 2, change the I2C bus from "0" to "1".

Using the scripts

To use these scripts, you need an I2C enabled Raspberry Pi. This manual shosw you how to install the right modules. You might need to enable the I2C modules, so, as root, do

modprobe i2c-dev

Now the root user can talk to the I2C bus. To enable an other user to talk to the I2C bus, without root privileges, run the following command as root:

sudo usermod -a -G i2c <username>

The scripts also use bc, a calculator program. Install this by running the following command as root:

apt-get install bc

The MPU-6050 boots up in a sleep mode, with all sensors disabled. To wake it up, run the mpu-6050-init script. Now you can start probing the MPU-6050. My first test was measuring the temperature, and see it change:

watch -n 0.5 mpu-6050-gettemp

If you grab hold of the sensor, you should see the reading go up.

Sample output for "./mpu-6050-getall":

Accelerometer:
X: F0D4
Y: 3874
Z: E3A4

Gyroscope:
X: FFF1
Y: FF03
Z: FFE2

Temperature:
25.791