Closed CloudyPadmal closed 2 years ago
Here is a software implementation in Python:
import time
from pslab.instrument.logic_analyzer import LogicAnalyzer
from pslab.instrument.waveform_generator import PWMGenerator
class HCSR04Soft(LogicAnalyzer, PWMGenerator):
def __init__(self, device):
self._device = device
LogicAnalyzer.__init__(self, self._device)
PWMGenerator.__init__(self, self._device)
self._measure_period = 60e-3
self._trigger_pulse_length = 10e-6
def estimate_distance(
self,
trig="SQ1",
echo="LA1",
average=10,
speed_of_sound=340
):
self.capture(channels=echo, events=2*average, block=False)
self.generate(
channels=trig,
frequency=self._measure_period ** -1,
duty_cycles=self._trigger_pulse_length / self._measure_period
)
time.sleep(self._measure_period * average)
self.set_state(**{trig.lower(): 0})
(t,) = self.fetch_data()
high_times = t[::2] - t[1::2]
return speed_of_sound * high_times.mean() / 2 * 1e-6
Haven't tested it since I don't have the sensor, but it should work. This implementation has a number of benefits over the firmware:
average
argument. Rerunning the firmware implementation the same number of times will be slower.@bessman sorry I didn't see the question of implementing this in Python earlier. I think that's a good idea and I just checked the code snippet you shared and it works! It's a neat trick to use the logic analyser to capture multiple samples to average the result. I like to go ahead with the Python path. Let me close this PR and link it to python-repo as an issue.
TODO:
SENSORS
block in statesInterval
functions from #122disable_IC
to logic analyzer; may be?