Skip to content

Commit 8337cdc

Browse files
authored
bno080x_heading_example
Using rotation vectors to find the heading value
1 parent f4e8dfd commit 8337cdc

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

examples/bno08x_find_heading.py

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

0 commit comments

Comments
 (0)