lis2mdl_compass.py
1 """ Display compass heading data from a calibrated magnetometer """ 2 3 import time 4 import math 5 import board 6 import busio 7 import adafruit_lis2mdl 8 9 i2c = busio.I2C(board.SCL, board.SDA) 10 sensor = adafruit_lis2mdl.LIS2MDL(i2c) 11 12 # You will need the calibration values from your magnetometer calibration 13 # these values are in uT and are in X, Y, Z order (min and max values). 14 # 15 # To get these values run the lis2mdl_calibrate.py script on your device. 16 # Twist the device around in 3D space while it calibrates. It will print 17 # some calibration values like these: 18 # ... 19 # Calibrating - X: -46.62, Y: -22.33, Z: -16.94 uT 20 # ... 21 # Calibration complete: 22 # hardiron_calibration = [[-63.5487, 33.0313], [-40.5145, 53.8293], [-43.7153, 55.5101]] 23 # 24 # You need t copy your own value for hardiron_calibration from the output and paste it 25 # into this script here: 26 hardiron_calibration = [[-61.4879, 34.4782], [-43.6714, 53.5662], [-40.7337, 52.4554]] 27 28 29 # This will take the magnetometer values, adjust them with the calibrations 30 # and return a new array with the XYZ values ranging from -100 to 100 31 def normalize(_magvals): 32 ret = [0, 0, 0] 33 for i, axis in enumerate(_magvals): 34 minv, maxv = hardiron_calibration[i] 35 axis = min(max(minv, axis), maxv) # keep within min/max calibration 36 ret[i] = (axis - minv) * 200 / (maxv - minv) + -100 37 return ret 38 39 40 while True: 41 magvals = sensor.magnetic 42 normvals = normalize(magvals) 43 print("magnetometer: %s -> %s" % (magvals, normvals)) 44 45 # we will only use X and Y for the compass calculations, so hold it level! 46 compass_heading = int(math.atan2(normvals[1], normvals[0]) * 180.0 / math.pi) 47 # compass_heading is between -180 and +180 since atan2 returns -pi to +pi 48 # this translates it to be between 0 and 360 49 compass_heading += 180 50 51 print("Heading:", compass_heading) 52 time.sleep(0.1)