1
- """ Display compass heading data five times per second """
1
+ """ Display compass heading data from a calibrated magnetometer """
2
+
2
3
import time
3
- from math import atan2 , degrees
4
+ import math
4
5
import board
5
6
import busio
6
7
import adafruit_lis2mdl
7
8
8
9
i2c = busio .I2C (board .SCL , board .SDA )
9
10
sensor = adafruit_lis2mdl .LIS2MDL (i2c )
10
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
+ hardiron_calibration = [[- 61.4879 , 34.4782 ], [- 43.6714 , 53.5662 ], [- 40.7337 , 52.4554 ]]
11
15
12
- def vector_2_degrees (x , y ):
13
- angle = degrees (atan2 (y , x ))
14
- if angle < 0 :
15
- angle += 360
16
- return angle
16
+ # This will take the magnetometer values, adjust them with the calibraitons
17
+ # and return a new array with the XYZ values ranging from -100 to 100
18
+ def normalize (magvals ):
19
+ ret = [0 , 0 , 0 ]
20
+ for i , axis in enumerate (magvals ):
21
+ minv , maxv = hardiron_calibration [i ]
22
+ axis = min (max (minv , axis ), maxv ) # keep within min/max calibration
23
+ ret [i ] = (axis - minv ) * 200 / (maxv - minv ) + - 100
24
+ return ret
17
25
18
26
19
- def get_heading (_sensor ):
20
- magnet_x , magnet_y , _ = _sensor .magnetic
21
- return vector_2_degrees (magnet_x , magnet_y )
27
+ while True :
28
+ magvals = sensor .magnetic
29
+ normvals = normalize (magvals )
30
+ print ("magnetometer: %s -> %s" % (magvals , normvals ))
22
31
32
+ # we will only use X and Y for the compass calculations, so hold it level!
33
+ compass_heading = int (math .atan2 (normvals [1 ], normvals [0 ]) * 180.0 / math .pi )
34
+ # compass_heading is between -180 and +180 since atan2 returns -pi to +pi
35
+ # this translates it to be between 0 and 360
36
+ compass_heading += 180
23
37
24
- while True :
25
- print ("heading: {:.2f} degrees" .format (get_heading (sensor )))
26
- time .sleep (0.2 )
38
+ print ("Heading:" , compass_heading )
39
+ time .sleep (0.1 )
0 commit comments