Skip to content

Commit ea0f05f

Browse files
authored
Merge pull request #14 from yugyesh/patch-3
bno080x_heading_example
2 parents 6bcf0ec + cb460d5 commit ea0f05f

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

examples/bno08x_find_heading.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# SPDX-FileCopyrightText: 2021 KC YUGESH
2+
# SPDX-License-Identifier: Unlicense
3+
4+
import time
5+
from math import atan2, sqrt, pi
6+
from board import SCL, SDA
7+
from busio import I2C
8+
from adafruit_bno08x import (
9+
BNO_REPORT_STEP_COUNTER,
10+
BNO_REPORT_ROTATION_VECTOR,
11+
BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR,
12+
)
13+
from adafruit_bno08x.i2c import BNO08X_I2C
14+
15+
i2c = I2C(SCL, SDA, frequency=800000)
16+
bno = BNO08X_I2C(i2c)
17+
bno.enable_feature(BNO_REPORT_STEP_COUNTER)
18+
bno.enable_feature(BNO_REPORT_ROTATION_VECTOR)
19+
bno.enable_feature(BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR)
20+
21+
# quat_real, quat_i, quat_j, quat_k
22+
23+
24+
def find_heading(dqw, dqx, dqy, dqz):
25+
norm = sqrt(dqw * dqw + dqx * dqx + dqy * dqy + dqz * dqz)
26+
dqw = dqw / norm
27+
dqx = dqx / norm
28+
dqy = dqy / norm
29+
dqz = dqz / norm
30+
31+
ysqr = dqy * dqy
32+
33+
t3 = +2.0 * (dqw * dqz + dqx * dqy)
34+
t4 = +1.0 - 2.0 * (ysqr + dqz * dqz)
35+
yaw_raw = atan2(t3, t4)
36+
yaw = yaw_raw * 180.0 / pi
37+
if yaw > 0:
38+
yaw = 360 - yaw
39+
else:
40+
yaw = abs(yaw)
41+
return yaw # heading in 360 clockwise
42+
43+
44+
while True:
45+
quat_i, quat_j, quat_k, quat_real = bno.quaternion
46+
heading = find_heading(quat_real, quat_i, quat_j, quat_k)
47+
print("Heading using rotation vector:", heading)
48+
49+
# the geomagnetic sensor is unstable
50+
# Heading is calculated using geomagnetic vector
51+
geo_quat_i, geo_quat_j, geo_quat_k, geo_quat_real = bno.geomagnetic_quaternion
52+
heading_geo = find_heading(geo_quat_real, geo_quat_i, geo_quat_j, geo_quat_k)
53+
print("Heading using geomagnetic rotation vector:", heading_geo)
54+
print("")
55+
time.sleep(0.1)

0 commit comments

Comments
 (0)