Skip to content

Instantly share code, notes, and snippets.

@ansarid
Last active March 4, 2022 14:22
Show Gist options
  • Save ansarid/23ab5561d7287cec4e5aacd7c72db1f1 to your computer and use it in GitHub Desktop.
Save ansarid/23ab5561d7287cec4e5aacd7c72db1f1 to your computer and use it in GitHub Desktop.
Reading the BeagleBone Blue MPU-9250 Compass

1. Install the RTIMU Python Library.

git clone https://github.com/RPi-Distro/RTIMULib
cd RTIMULib/Linux/python
sudo python3 setup.py install

2. Compile calibration code.

cd ../RTIMULibCal/
make
sudo make install

3. Configure Calibration File.

First run RTIMULibCal to create the RTIMULib.ini file.

  • Edit RTIMULib.ini.
  • Find each variable in RTIMULib.ini and set it to the values below.
IMUType=7
BusIsI2C=true
I2CBus=2
I2CSlaveAddress=104

4. Calibrate the Magnetometer.

  • Run RTIMULibCal inside the RTIMULib/Linux/RTIMULibCal
  • Follow calibration instructions. (I had good results after using only m - calibrate magnetometer with min/max)
    • After you finish the calibration, RTIMULibCal writes the calibration values to the RTIMULib.ini file.

5. Create an example project.

mkdir compass_example
cd compass_example
  • Copy RTIMULib.ini from RTIMULib/Linux/RTIMULibCal/ to the compass_example folder.

6. Copy the compass_ex.py to your compass_example folder.

wget https://gist.githubusercontent.com/ansarid/23ab5561d7287cec4e5aacd7c72db1f1/raw/4ad2881648d09bb5f3fef774c486ff9615f9cb4c/compass_ex.py

7. Your folder should look like this:

compass_example
    ├ RTIMULib.ini
    └ compass_ex.py

8. Run compass_ex.py.

python3 compass_ex.py

import os
import sys
import math
import time
import RTIMU
import os.path
SETTINGS_FILE = "RTIMULib"
s = RTIMU.Settings(SETTINGS_FILE)
imu = RTIMU.RTIMU(s)
if (not imu.IMUInit()):
print("IMU Init Failed")
sys.exit(1)
else:
print("IMU Init Succeeded")
imu.setSlerpPower(0.02)
imu.setGyroEnable(True)
imu.setAccelEnable(True)
imu.setCompassEnable(True)
poll_interval = imu.IMUGetPollInterval()
previous_angle = 0
current_angle = 20
while True:
if imu.IMURead():
data = imu.getIMUData()
magX = data["compass"][0]
magY = data["compass"][1]
heading = 180 * math.atan2(magY,magX)/math.pi
if heading < 0:
heading += 360
heading = int(heading)
print(heading)
current_angle = heading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment