pysense with mpu9250

  • import machine, time, math, pycom, os
    from machine import I2C
    from mpu9250 import MPU9250
    from ak8963 import AK8963
    i2c = I2C(0, mode=I2C.MASTER, pins=('P10','P11'))
    sensor = MPU9250(i2c)
    sensor2= AK8963(i2c)
    #Declination Ankara, TURKEY
    print("MPU9250 id: " + hex(sensor.whoami))
    print("AK8963 id: " + hex(sensor2.whoami))
    print("To Calibrate Magnetometer please draw an 8 on the air 1 minute")
    sensor2= AK8963(i2c,offset=offset, scale=scale)
    print("Calibration finished (offset), (scale): ",cali)
    while True:
      print('acc :',sensor.acceleration)
      print('mag :',sensor.magnetic)
     #Compass Direction
      if (y > 0):
      if (y < 0):
      if (y==0) & (x < 0):
      if (y==0) & (x > 0):
      #print('mx=',x,'uT, my=',y,'uT, mz=',z,'uT')
      print('Compass Direction:',round(heading+decli),'degrees')
      # Turn light on Green when 0 degrees
      if (round(heading+decli)==0):
      if (round(heading+decli)!=0):

    I shared the code above. As seen in the code, I am using pysense p10 and p11 pins and made my cable connection that way.
    Screen Shot 2020-08-20 at 15.26.52.png
    I got such an error.
    I read on the forum that the pysense i2c bus fail error with the mpu9250.
    Is this true?
    What can I do?
    Can you help me?
    Do you have an idea?
    Thanks pycom family!

  • The best way to calibrate a magnetic compass is outside. As concrete and metal objects will affect the magnetic field orientation, and thus the sensor output. Also, keep the sensor level, as rotation around other axes will require additional calibrations (you could use the accelerometer in the device to account for this ). i believe there are many examples on the internet using this or similar sensors :)


  • @Gijs
    Thank you so much.
    I have applied the information you provided and the code is working.
    but I'm having trouble with calibration. Is there any advice you can give about this? Thank you again.

  • Im not sure exactly what you mean, but im sensing you have 2 additional sensor attached over the i2c bus and soldered the i2c wires to the Pysense pins. Do you have both sensors connected? It seems line 9 is the definition of

    sensor2= AK8963(i2c)

    Meaning it cannot initialize the AK8963 sensor.

    Did you try using Pins P9 and P10 instead? According to the datasheet, they are the SDA and SCL pins respectively. Also, Im not too familiar with the libraries. Make sure you have SDA and SCL defined in the correct order, and have the sensors powered up. It seems the I2C is not able to communicate to the sensors, but your log is too limited to properly examine.
    What happens previous to the error?

Log in to reply

Pycom on Twitter