Skip to content

Commit 891b5bc

Browse files
committed
Fixed Ultrasonic Timeout Issue
1 parent b3dc529 commit 891b5bc

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

XRPLib/rangefinder.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ def __init__(self, trigger_pin:int, echo_pin:int, timeout_us:int=500*2*30):
3636
# Init echo pin (in)
3737
self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)
3838

39+
self.cms = 0
40+
self.last_echo_time = 0
41+
self.cache_time_us = 3000
42+
3943
def _send_pulse_and_wait(self):
4044
"""
4145
Send the pulse to trigger and listen on echo pin.
@@ -57,6 +61,9 @@ def distance(self) -> float:
5761
"""
5862
Get the distance in centimeters by measuring the echo pulse time
5963
"""
64+
if time.ticks_diff(time.ticks_us(), self.last_echo_time) < self.cache_time_us and not self.cms == 65535:
65+
return self.cms
66+
6067
try:
6168
pulse_time = self._send_pulse_and_wait()
6269
if pulse_time <= 0:
@@ -72,8 +79,9 @@ def distance(self) -> float:
7279
# (the pulse walk the distance twice) and by 29.1 becasue
7380
# the sound speed on air (343.2 m/s), that It's equivalent to
7481
# 0.034320 cm/us that is 1cm each 29.1us
75-
cms = (pulse_time / 2) / 29.1
76-
return cms
82+
self.cms = (pulse_time / 2) / 29.1
83+
self.last_echo_time = time.ticks_us()
84+
return self.cms
7785

7886
def _delay_us(self, delay:int):
7987
"""

0 commit comments

Comments
 (0)