lis2mdl_calibrate.py
1 """ Calibrate the magnetometer and print out the hard-iron calibrations """ 2 3 import time 4 import board 5 import busio 6 import adafruit_lis2mdl 7 8 i2c = busio.I2C(board.SCL, board.SDA) 9 magnetometer = adafruit_lis2mdl.LIS2MDL(i2c) 10 11 # calibration for magnetometer X (min, max), Y and Z 12 hardiron_calibration = [[1000, -1000], [1000, -1000], [1000, -1000]] 13 14 15 def calibrate(): 16 start_time = time.monotonic() 17 18 # Update the high and low extremes 19 while time.monotonic() - start_time < 10.0: 20 magval = magnetometer.magnetic 21 print("Calibrating - X:{0:10.2f}, Y:{1:10.2f}, Z:{2:10.2f} uT".format(*magval)) 22 for i, axis in enumerate(magval): 23 hardiron_calibration[i][0] = min(hardiron_calibration[i][0], axis) 24 hardiron_calibration[i][1] = max(hardiron_calibration[i][1], axis) 25 print("Calibration complete:") 26 print("hardiron_calibration =", hardiron_calibration) 27 28 29 print("Prepare to calibrate! Twist the magnetometer around in 3D in...") 30 print("3...") 31 time.sleep(1) 32 print("2...") 33 time.sleep(1) 34 print("1...") 35 time.sleep(1) 36 37 calibrate()