Skip to content

Commit 972d54d

Browse files
authored
Added comments to each section of code
I was finding it hard to understand the code, so I worked it out and added lots of comments that should make the process quicker for others.
1 parent fa68ea3 commit 972d54d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

examples/magnetometer.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,37 +16,61 @@
1616
Y = 1
1717
Z = 2
1818

19+
# The two axes which relate to heading, depends on orientation of the sensor
20+
# Think Left & Right, Forwards and Back, ignoring Up and Down
1921
AXES = Y, Z
2022

23+
# Initialise the imu
2124
imu = ICM20948()
2225

26+
# Store an initial two readings from the Magnetometer
2327
amin = list(imu.read_magnetometer_data())
2428
amax = list(imu.read_magnetometer_data())
2529

2630
while True:
31+
# Read the current, uncalibrated, X, Y & Z magnetic values from the magnetometer and save as a list
2732
mag = list(imu.read_magnetometer_data())
33+
34+
# Step through each uncalibrated X, Y & Z magnetic value and calibrate them the best we can
2835
for i in range(3):
2936
v = mag[i]
37+
# If our current reading (mag) is less than our stored minimum reading (amin), then save a new minimum reading
38+
# ie save a new lowest possible value for our calibration of this axis
3039
if v < amin[i]:
3140
amin[i] = v
41+
# If our current reading (mag) is greater than our stored maximum reading (amax), then save a new maximum reading
42+
# ie save a new highest possible value for our calibration of this axis
3243
if v > amax[i]:
3344
amax[i] = v
45+
46+
# Calibrate value by removing any offset when compared to the lowest reading seen for this axes
3447
mag[i] -= amin[i]
48+
49+
# Scale value based on the higest range of values seen for this axes
50+
# Creates a calibrated value between 0 and 1 representing magnetic value
3551
try:
3652
mag[i] /= amax[i] - amin[i]
3753
except ZeroDivisionError:
3854
pass
55+
# Shift magnetic values to between -0.5 and 0.5 to enable the trig to work
3956
mag[i] -= 0.5
4057

58+
# Convert from Gauss values in the appropriate 2 axis to a heading in Radians using trig
59+
# Note this does not compensate for tilt
4160
heading = math.atan2(
4261
mag[AXES[0]],
4362
mag[AXES[1]])
4463

64+
# If heading is negative, convert to positive, 2 x pi is a full circle in Radians
4565
if heading < 0:
4666
heading += 2 * math.pi
67+
68+
# Convert heading from Radians to Degrees
4769
heading = math.degrees(heading)
70+
# Round heading to nearest full degree
4871
heading = round(heading)
4972

73+
# Note: Headings will not be correct until a full 360 deg calibration turn has been completed to generate amin and amax data
5074
print("Heading: {}".format(heading))
5175

5276
time.sleep(0.1)

0 commit comments

Comments
 (0)