Skip to content

Commit 61b709a

Browse files
committed
linting, cleaning up examples
1 parent c90b57e commit 61b709a

File tree

5 files changed

+300
-188
lines changed

5 files changed

+300
-188
lines changed

adafruit_bno08x/__init__.py

+22-27
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# pylint:disable=too-many-lines
12
# SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries
23
#
34
# SPDX-License-Identifier: MIT
@@ -198,20 +199,6 @@ def _elapsed(start_time):
198199
return time.monotonic() - start_time
199200

200201

201-
def elapsed_time(func):
202-
"""Print the runtime of the decorated function"""
203-
204-
def wrapper_timer(*args, **kwargs):
205-
start_time = time.monotonic() # 1
206-
value = func(*args, **kwargs)
207-
end_time = time.monotonic() # 2
208-
run_time = end_time - start_time # 3
209-
print("Finished", func.__name__, "in", (run_time * 1000.0), "ms")
210-
return value
211-
212-
return wrapper_timer
213-
214-
215202
############ PACKET PARSING ###########################
216203
def _parse_sensor_report_data(report_bytes):
217204
"""Parses reports with only 16-bit fields"""
@@ -520,9 +507,15 @@ def __init__(self, reset=None, debug=False):
520507

521508
def initialize(self):
522509
"""Initialize the sensor"""
523-
self.hard_reset()
524-
self.soft_reset()
525-
if not self._check_id():
510+
for _ in range(3):
511+
self.hard_reset()
512+
self.soft_reset()
513+
try:
514+
if self._check_id():
515+
break
516+
except: # pylint:disable=bare-except
517+
time.sleep(0.5)
518+
else:
526519
raise RuntimeError("Could not read ID")
527520

528521
@property
@@ -792,7 +785,6 @@ def _process_available_packets(self, max_packets=None):
792785
self._dbg("")
793786
# print("Processed", processed_count, "packets")
794787
self._dbg("")
795-
# we'll probably need an exit here for fast sensor rates
796788
self._dbg("")
797789
self._dbg(" ** DONE! **")
798790

@@ -875,8 +867,13 @@ def _handle_control_report(self, report_id, report_bytes):
875867
def _handle_command_response(self, report_bytes):
876868
(report_body, response_values) = _parse_command_response(report_bytes)
877869

878-
# report_id, seq_number, command, command_seq_number, response_seq_number) = report_body
879-
_report_id, _sequence_number, command = report_body
870+
(
871+
_report_id,
872+
_seq_number,
873+
command,
874+
_command_seq_number,
875+
_response_seq_number,
876+
) = report_body
880877

881878
# status, accel_en, gyro_en, mag_en, planar_en, table_en, *_reserved) = response_values
882879
command_status, *_rest = response_values
@@ -902,7 +899,7 @@ def _process_report(self, report_id, report_bytes):
902899
if (packet_index % 4) == 0:
903900
outstr += "\nDBG::\t\t[0x{:02X}] ".format(packet_index)
904901
outstr += "0x{:02X} ".format(packet_byte)
905-
print(outstr)
902+
self._dbg(outstr)
906903
self._dbg("")
907904

908905
if report_id == BNO_REPORT_STEP_COUNTER:
@@ -941,7 +938,6 @@ def _process_report(self, report_id, report_bytes):
941938
def _get_feature_enable_report(
942939
feature_id, report_interval=_DEFAULT_REPORT_INTERVAL, sensor_specific_config=0
943940
):
944-
# TODO !!! ALLOCATION !!!
945941
set_feature_report = bytearray(17)
946942
set_feature_report[0] = _SET_FEATURE_COMMAND
947943
set_feature_report[1] = feature_id
@@ -970,7 +966,7 @@ def enable_feature(self, feature_id):
970966
self._dbg("Enabling feature depencency:", feature_dependency)
971967
self.enable_feature(feature_dependency)
972968

973-
print("Enabling", feature_id)
969+
self._dbg("Enabling", feature_id)
974970
self._send_packet(_BNO_CHANNEL_CONTROL, set_feature_report)
975971

976972
start_time = time.monotonic() # 1
@@ -1040,7 +1036,6 @@ def hard_reset(self):
10401036
"""Hardware reset the sensor to an initial unconfigured state"""
10411037
if not self._reset:
10421038
return
1043-
# print("Hard resetting...")
10441039
import digitalio # pylint:disable=import-outside-toplevel
10451040

10461041
self._reset.direction = digitalio.Direction.OUTPUT
@@ -1049,11 +1044,11 @@ def hard_reset(self):
10491044
self._reset.value = False
10501045
time.sleep(0.01)
10511046
self._reset.value = True
1052-
time.sleep(0.5)
1047+
time.sleep(0.01)
10531048

10541049
def soft_reset(self):
10551050
"""Reset the sensor to an initial unconfigured state"""
1056-
print("Soft resetting...", end="")
1051+
self._dbg("Soft resetting...", end="")
10571052
data = bytearray(1)
10581053
data[0] = 1
10591054
_seq = self._send_packet(BNO_CHANNEL_EXE, data)
@@ -1067,7 +1062,7 @@ def soft_reset(self):
10671062
except PacketError:
10681063
time.sleep(0.5)
10691064

1070-
print("OK!")
1065+
self._dbg("OK!")
10711066
# all is good!
10721067

10731068
def _send_packet(self, channel, data):

adafruit_bno08x/spi.py

+22-19
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from digitalio import Direction, Pull
1313
import adafruit_bus_device.spi_device as spi_device
14-
from . import BNO08X, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, _elapsed, Packet, PacketError
14+
from . import BNO08X, DATA_BUFFER_SIZE, _elapsed, Packet, PacketError
1515

1616

1717
class BNO08X_SPI(BNO08X):
@@ -31,24 +31,21 @@ class BNO08X_SPI(BNO08X):
3131
# """
3232

3333
def __init__(
34-
self, spi_bus, cspin, intpin, wakepin, resetpin, baudrate=4000000, debug=False
34+
self, spi_bus, cspin, intpin, resetpin, baudrate=1000000, debug=False
3535
): # pylint:disable=too-many-arguments
3636
self._spi = spi_device.SPIDevice(
3737
spi_bus, cspin, baudrate=baudrate, polarity=1, phase=1
3838
)
3939
self._int = intpin
40-
self._wake = wakepin
4140
super().__init__(resetpin, debug)
4241

4342
def hard_reset(self):
4443
"""Hardware reset the sensor to an initial unconfigured state"""
4544
self._reset.direction = Direction.OUTPUT
46-
self._wake.direction = Direction.OUTPUT
4745
self._int.direction = Direction.INPUT
4846
self._int.pull = Pull.UP
4947

5048
print("Hard resetting...")
51-
self._wake.value = True # set PS0 high (PS1 also must be tied high)
5249
self._reset.value = True # perform hardware reset
5350
time.sleep(0.01)
5451
self._reset.value = False
@@ -65,46 +62,50 @@ def _wait_for_int(self):
6562
if not self._int.value:
6663
break
6764
else:
68-
raise RuntimeError("Could not wake up")
65+
self.hard_reset()
66+
# raise RuntimeError("Could not wake up")
6967
# print("OK")
7068

7169
def soft_reset(self):
7270
"""Reset the sensor to an initial unconfigured state"""
73-
print("Soft resetting...", end="")
74-
data = bytearray(1)
75-
data[0] = 1
76-
_seq = self._send_packet(BNO_CHANNEL_EXE, data)
77-
time.sleep(0.5)
71+
# print("Soft resetting...", end="")
72+
# data = bytearray(1)
73+
# data[0] = 1
74+
# _seq = self._send_packet(BNO_CHANNEL_EXE, data)
75+
# time.sleep(0.5)
7876

7977
for _i in range(3):
8078
try:
8179
_packet = self._read_packet()
8280
except PacketError:
83-
time.sleep(0.5)
84-
print("OK!")
81+
time.sleep(0.1)
82+
# print("OK!")
8583
# all is good!
8684

8785
def _read_into(self, buf, start=0, end=None):
8886
self._wait_for_int()
8987

9088
with self._spi as spi:
91-
spi.readinto(buf, start=start, end=end)
92-
# print("SPI Read buffer: ", [hex(i) for i in buf[start:end]])
89+
spi.readinto(buf, start=start, end=end, write_value=0x00)
90+
# print("SPI Read buffer (", end-start, "b )", [hex(i) for i in buf[start:end]])
9391

9492
def _read_header(self):
9593
"""Reads the first 4 bytes available as a header"""
9694
self._wait_for_int()
9795

9896
# read header
9997
with self._spi as spi:
100-
spi.readinto(self._data_buffer, end=4)
98+
spi.readinto(self._data_buffer, end=4, write_value=0x00)
10199
self._dbg("")
102-
# print("SHTP READ packet header: ", [hex(x) for x in self._data_buffer[0:4]])
100+
self._dbg("SHTP READ packet header: ", [hex(x) for x in self._data_buffer[0:4]])
103101

104102
def _read_packet(self):
105103
self._read_header()
104+
halfpacket = False
106105

107-
# print([hex(x) for x in self._data_buffer[0:4]])
106+
print([hex(x) for x in self._data_buffer[0:4]])
107+
if self._data_buffer[1] & 0x80:
108+
halfpacket = True
108109
header = Packet.header_from_buffer(self._data_buffer)
109110
packet_byte_count = header.packet_byte_count
110111
channel_number = header.channel_number
@@ -126,6 +127,8 @@ def _read_packet(self):
126127
self._read_into(self._data_buffer, start=0, end=packet_byte_count)
127128
# print("Packet: ", [hex(i) for i in self._data_buffer[0:packet_byte_count]])
128129

130+
if halfpacket:
131+
raise PacketError("read partial packet")
129132
new_packet = Packet(self._data_buffer)
130133
if self._debug:
131134
print(new_packet)
@@ -158,7 +161,7 @@ def _send_packet(self, channel, data):
158161
self._wait_for_int()
159162
with self._spi as spi:
160163
spi.write(self._data_buffer, end=write_length)
161-
# print("Sending: ", [hex(x) for x in self._data_buffer[0:write_length]])
164+
self._dbg("Sending: ", [hex(x) for x in self._data_buffer[0:write_length]])
162165
self._sequence_number[channel] = (self._sequence_number[channel] + 1) % 256
163166
return self._sequence_number[channel]
164167

examples/bno08x_more_reports.py

+137
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
# SPDX-FileCopyrightText: 2020 Bryan Siepert, written for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: Unlicense
4+
import time
5+
import board
6+
import busio
7+
from digitalio import DigitalInOut
8+
import adafruit_bno08x
9+
from adafruit_bno08x.i2c import BNO08X_I2C
10+
11+
i2c = busio.I2C(board.SCL, board.SDA, frequency=800000)
12+
reset_pin = DigitalInOut(board.D5)
13+
bno = BNO08X_I2C(i2c, reset=reset_pin, debug=False)
14+
15+
# TODO: UPDATE UART/SPI
16+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACCELEROMETER)
17+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE)
18+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETOMETER)
19+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_LINEAR_ACCELERATION)
20+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_ROTATION_VECTOR)
21+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR)
22+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_GAME_ROTATION_VECTOR)
23+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_STEP_COUNTER)
24+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_STABILITY_CLASSIFIER)
25+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACTIVITY_CLASSIFIER)
26+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_SHAKE_DETECTOR)
27+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_ACCELEROMETER)
28+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_GYROSCOPE)
29+
bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_MAGNETOMETER)
30+
31+
while True:
32+
time.sleep(0.1)
33+
34+
print("Acceleration:")
35+
accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member
36+
print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z))
37+
print("")
38+
39+
print("Gyro:")
40+
gyro_x, gyro_y, gyro_z = bno.gyro # pylint:disable=no-member
41+
print("X: %0.6f Y: %0.6f Z: %0.6f rads/s" % (gyro_x, gyro_y, gyro_z))
42+
print("")
43+
44+
print("Magnetometer:")
45+
mag_x, mag_y, mag_z = bno.magnetic # pylint:disable=no-member
46+
print("X: %0.6f Y: %0.6f Z: %0.6f uT" % (mag_x, mag_y, mag_z))
47+
print("")
48+
49+
print("Linear Acceleration:")
50+
(
51+
linear_accel_x,
52+
linear_accel_y,
53+
linear_accel_z,
54+
) = bno.linear_acceleration # pylint:disable=no-member
55+
print(
56+
"X: %0.6f Y: %0.6f Z: %0.6f m/s^2"
57+
% (linear_accel_x, linear_accel_y, linear_accel_z)
58+
)
59+
print("")
60+
61+
print("Rotation Vector Quaternion:")
62+
quat_i, quat_j, quat_k, quat_real = bno.quaternion # pylint:disable=no-member
63+
print(
64+
"I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real)
65+
)
66+
print("")
67+
68+
print("Geomagnetic Rotation Vector Quaternion:")
69+
(
70+
geo_quat_i,
71+
geo_quat_j,
72+
geo_quat_k,
73+
geo_quat_real,
74+
) = bno.geomagnetic_quaternion # pylint:disable=no-member
75+
print(
76+
"I: %0.6f J: %0.6f K: %0.6f Real: %0.6f"
77+
% (geo_quat_i, geo_quat_j, geo_quat_k, geo_quat_real)
78+
)
79+
# print("")
80+
81+
print("Game Rotation Vector Quaternion:")
82+
(
83+
game_quat_i,
84+
game_quat_j,
85+
game_quat_k,
86+
game_quat_real,
87+
) = bno.game_quaternion # pylint:disable=no-member
88+
print(
89+
"I: %0.6f J: %0.6f K: %0.6f Real: %0.6f"
90+
% (game_quat_i, game_quat_j, game_quat_k, game_quat_real)
91+
)
92+
print("")
93+
94+
print("Steps detected:", bno.steps)
95+
print("")
96+
97+
print("Stability classification:", bno.stability_classification)
98+
print("")
99+
100+
activity_classification = bno.activity_classification
101+
most_likely = activity_classification["most_likely"]
102+
print(
103+
"Activity classification:",
104+
most_likely,
105+
"confidence: %d/100" % activity_classification[most_likely],
106+
)
107+
108+
print("Raw Acceleration:")
109+
(raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_acceleration
110+
print(
111+
"X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format(
112+
raw_accel_x, raw_accel_y, raw_accel_z
113+
)
114+
)
115+
print("")
116+
117+
print("Raw Gyro:")
118+
(raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_gyro
119+
print(
120+
"X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format(
121+
raw_accel_x, raw_accel_y, raw_accel_z
122+
)
123+
)
124+
print("")
125+
126+
print("Raw Magnetometer:")
127+
(raw_mag_x, raw_mag_y, raw_mag_z,) = bno.raw_magnetic
128+
print(
129+
"X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format(
130+
raw_mag_x, raw_mag_y, raw_mag_z
131+
)
132+
)
133+
print("")
134+
time.sleep(0.4)
135+
if bno.shake:
136+
print("SHAKE DETECTED!")
137+
print("")

0 commit comments

Comments
 (0)