Skip to content

Commit 5be8367

Browse files
committed
Handle timeout errors in Modulino Distance
1 parent d6e799d commit 5be8367

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/modulino/distance.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,22 @@ def __init__(self, i2c_bus = None, address: int | None = None) -> None:
2525
self.sensor.start_ranging()
2626

2727
@property
28-
def _distance_raw(self) -> int:
28+
def _distance_raw(self) -> int | None:
2929
"""
3030
Reads the raw distance value from the sensor and clears the interrupt.
3131
3232
Returns:
3333
int: The distance in centimeters.
3434
"""
35-
while not self.sensor.data_ready:
36-
pass
37-
self.sensor.clear_interrupt()
38-
return self.sensor.distance
35+
try:
36+
while not self.sensor.data_ready:
37+
pass
38+
self.sensor.clear_interrupt()
39+
sensor_value = self.sensor.distance
40+
return sensor_value
41+
except OSError:
42+
# Catch timeout errors
43+
return None
3944

4045
@property
4146
def distance(self) -> int:
@@ -46,5 +51,5 @@ def distance(self) -> int:
4651
while True:
4752
raw_distance = self._distance_raw
4853
# Filter out invalid readings
49-
if raw_distance > 0:
54+
if not raw_distance is None and raw_distance > 0:
5055
return raw_distance

0 commit comments

Comments
 (0)