Skip to content

Commit dd95a65

Browse files
committed
Added calibrate example
1 parent cd60762 commit dd95a65

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

examples/calibrate.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
##
2+
## Calibration routine modified from https://github.com/adafruit/glitterpos/
3+
##
4+
## Will calibrate magnetic and gyroscope
5+
##
6+
## Usage: run calibrate.calibrate()
7+
## Ensure your sensor is set
8+
##
9+
## For magnetic move your device all around rotating in all directions
10+
## For gyro leave it perfectly still
11+
## The program will print both values but only the one you are testing for is valid
12+
##
13+
## For another method see:
14+
## https://learn.adafruit.com/how-to-fuse-motion-sensor-data-into-ahrs-orientation-euler-quaternions/overview
15+
##
16+
17+
import time
18+
import math
19+
import board
20+
import busio
21+
import adafruit_lsm9ds1
22+
23+
def map_range(x, in_min, in_max, out_min, out_max):
24+
"""
25+
Maps a number from one range to another.
26+
:return: Returns value mapped to new range
27+
:rtype: float
28+
"""
29+
mapped = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
30+
if out_min <= out_max:
31+
return max(min(mapped, out_max), out_min)
32+
33+
return min(max(mapped, out_max), out_min)
34+
35+
def calibrate():
36+
"""
37+
Calibrates a magnometer or gyroscope
38+
Gyroscope values are in rads/s
39+
"""
40+
i2c = busio.I2C(board.A3, board.A2)
41+
sensor = adafruit_lsm9ds1.LSM9DS1_I2C(i2c)
42+
43+
MAG_MIN = [1000, 1000, 1000]
44+
MAG_MAX = [-1000, -1000, -1000]
45+
46+
lastDisplayTime = time.monotonic()
47+
xavg = 0
48+
yavg = 0
49+
zavg = 0
50+
countavg = 0
51+
52+
while True:
53+
x, y, z = sensor.magnetic
54+
mag_vals = [x, y, z]
55+
56+
for i in range(3):
57+
MAG_MIN[i] = min(MAG_MIN[i], mag_vals[i])
58+
MAG_MAX[i] = max(MAG_MAX[i], mag_vals[i])
59+
60+
gx, gy, gz = sensor.gyro
61+
62+
gx = gx * 3.14159 / 180
63+
xavg += gx
64+
gy = gy * 3.14159 / 180
65+
yavg += gy
66+
gz = gz * 3.14159 / 180
67+
zavg += gz
68+
countavg += 1
69+
70+
if (time.monotonic() - lastDisplayTime >= 3):
71+
print("Uncalibrated:", x, y, z)
72+
cal_x = map_range(x, MAG_MIN[0], MAG_MAX[0], -1, 1)
73+
cal_y = map_range(y, MAG_MIN[1], MAG_MAX[1], -1, 1)
74+
cal_z = map_range(z, MAG_MIN[2], MAG_MAX[2], -1, 1)
75+
print("Calibrated: ", cal_x, cal_y, cal_z)
76+
print("MAG_MIN =", MAG_MIN)
77+
print("MAG_MAX =", MAG_MAX)
78+
print("Uncalibrated gyro: ", (gx, gy, gz))
79+
print("Gyro: ", (xavg / countavg, yavg / countavg, zavg / countavg))
80+
81+
lastDisplayTime = time.monotonic()

0 commit comments

Comments
 (0)